Skip to main content
March 23, 2026Dan Rodney/13 min read

Fundamentals of JavaScript Code

Master Essential JavaScript Concepts and Syntax

Core JavaScript Concepts You'll Learn

Methods & Arguments

Learn how JavaScript methods work as actions that perform tasks. Understand how to pass data through arguments to control method behavior.

Variables & Data Types

Master variable declaration, assignment, and understand the differences between strings, numbers, and booleans in JavaScript.

Console & Debugging

Use Chrome DevTools Console for testing code, viewing output, and identifying errors in your JavaScript programs.

Topics Covered in This JavaScript Tutorial:

This comprehensive tutorial covers essential JavaScript fundamentals: methods (including alerts and console.log), variable declaration and management, mastering Chrome's DevTools JavaScript Console, the critical importance of quotes in JavaScript syntax, distinguishing between numbers and strings, string concatenation techniques, Booleans and conditional logic basics, plus error message interpretation and JavaScript troubleshooting strategies.

Exercise Preview

preview fundamentals

Exercise Overview

Before diving into real-world JavaScript applications, you must master the foundational concepts and syntax that form the backbone of modern web development. These core principles serve as essential building blocks for sophisticated scripts and applications. In today's development landscape, JavaScript powers everything from interactive user interfaces to server-side applications, making these fundamentals more crucial than ever.

Getting Started

  1. Launch your preferred code editor (Visual Studio Code, Sublime Text, or similar modern editor). If you're attending a Noble Desktop class, use Visual Studio Code as your primary development environment.
  2. In your code editor, close any existing files to maintain a clean workspace.
  3. For this exercise, we'll work with the JavaScript-Fundamentals folder located in Desktop > Class Files > JavaScript Class. Open this folder in your code editor's file explorer (Visual Studio Code provides excellent folder management capabilities).
  4. In your code editor, open index.html from the JavaScript-Fundamentals folder.
  5. Preview index.html in Chrome. We're using Chrome specifically because of its superior DevTools, which remain the industry standard for JavaScript debugging and development.

    NOTE: If you're using Visual Studio Code with the Live Server or open in browser extension installed, press Option–B (Mac) or Alt–B (Windows) to launch the HTML document directly in your browser.

    Alternatively, open the page manually through your browser. Press Cmd–O (Mac) or Ctrl–O (Windows), navigate to the JavaScript Class folder, then JavaScript-Fundamentals, and double-click index.html.

  6. Notice this is a blank HTML page. This intentional simplicity allows us to focus entirely on JavaScript concepts without visual distractions.

  7. Keep this page open in your browser throughout the exercise, refreshing it to see your code changes in real-time.

Setting Up Your Development Environment

1

Launch Code Editor

Open Visual Studio Code or your preferred code editor. Close any existing files to start fresh.

2

Open Project Folder

Navigate to JavaScript-Fundamentals folder in Desktop > Class Files > JavaScript Class and open it in your editor.

3

Preview in Chrome

Open index.html in Chrome browser using Option-B (Mac) or ALT-B (Windows) if using VS Code with browser extension.

Adding JavaScript to a Webpage

JavaScript code must be wrapped in a script tag to execute properly. While JavaScript can be placed anywhere in an HTML document, we'll position it in the head section for this tutorial to ensure it loads before any page content.

  1. Switch back to index.html in your code editor.
  2. Add the following bold code before the closing </head> tag:

    <title>JavaScript Fundamentals</title>
       <script></script>
    </head>
  3. Inside the script tag, add the following bold code:

    <script>
       alert('Hello');
    </script>

    NOTE: alert(data) is a JavaScript method that displays a browser dialog containing the specified data. Think of methods as the verbs of JavaScript—they perform actions and execute functionality.

    Script Tag Placement

    JavaScript code must be wrapped in script tags, typically placed in the head section of your HTML document. This ensures the code loads before the page content.

Methods & Arguments

Methods are actions that perform specific tasks. The alert() method's action is opening a dialog box. Methods follow a consistent format: methodName followed by parentheses containing optional data called arguments.

Code format: method(argument)

Arguments are the data passed into a method's parentheses. In the alert() method above, the argument is 'Hello'—the text that will appear in the dialog box.

  • Save the file and reload the page in your browser.

    You should see a dialog displaying Hello. Notice the text appears without quotes, even though quotes were present in your code. This distinction between code syntax and output display is fundamental to understanding JavaScript.

    Click OK to close the alert.

  • Methods vs Arguments

    FeatureMethodsArguments
    DefinitionActions that perform tasksData passed to methods
    RoleThe verbs of JavaScriptInformation for the action
    SyntaxmethodName()Inside parentheses
    Examplealert()'Hello'
    Recommended: Think of methods as actions and arguments as the specific instructions for those actions.

    The Console

    The Console is an indispensable browser developer tool used for testing code, debugging applications, and monitoring script execution. Let's output our greeting to the Console using the log() method on JavaScript's console object—a technique you'll use extensively in professional development.

    1. Switch back to your code editor.
    2. After the alert, add a console.log command as shown below in bold:

      <script>
         alert('Hello');
         console.log('Hello from console');
      </script>
    3. Save the file and reload the page in your browser.

      The alert still appears, but the console message requires the developer tools to view—a more discreet debugging method preferred in production environments.

    4. Click OK to close the alert.
    5. Ctrl–click (Mac) or Right–click (Windows) on the page, then choose Inspect to open Chrome's DevTools.
    6. At the top of the DevTools window, click the Console tab.

      Here you'll see the message Hello from console—demonstrating how console.log provides a non-intrusive way to monitor your code's execution.

    Accessing Chrome DevTools Console

    1

    Right-Click Page

    CTRL-click (Mac) or Right-click (Windows) on any webpage to open the context menu.

    2

    Choose Inspect

    Select 'Inspect' from the context menu to open Chrome DevTools panel.

    3

    Click Console Tab

    Navigate to the Console tab at the top of the DevTools window to view JavaScript output and errors.

    Variables

    A variable is a named container that stores data values. In modern JavaScript, variables must be declared (created) and assigned a value. While you can declare variables using either let or var, let is the preferred, contemporary syntax due to its better scoping behavior and reduced potential for errors.

    JavaScript is strictly case-sensitive, so precise typing of variable names is crucial: myvar, myVar, Myvar, myVar, and MYVAR are all completely different variables that can coexist in the same program.

    1. Switch back to your code editor.
    2. Make the following changes shown in bold. Pay meticulous attention to capitalization, as JavaScript's case-sensitivity makes this critical:

      <script>
         let myMessage = 'Hello';
         alert(myMessage);
         console.log('Hello from console');
      </script>
      Let's analyze this code structure:
      • We created a variable named myMessage that stores the text 'Hello'
      • The let keyword declares (creates) a new variable in the current scope.
      • The alert now displays the variable's contents. Notice the absence of quotes around the variable name inside the alert() method—this tells JavaScript to use the variable's value, not its name.
    3. Save and reload the page in the browser.

      • The alert should display the same Hello message, but now it's retrieving that text from the myMessage variable's stored value.
      • Click OK to close the alert.
    Case Sensitivity Alert

    JavaScript is case-sensitive! Variables myvar, myVar, Myvar, and MYVAR are all completely different. Pay close attention to capitalization when naming and using variables.

    Variable Declaration: let vs var

    Featureletvar
    Modern StandardPreferred syntaxLegacy syntax
    Best PracticeRecommendedDiscouraged
    UsageUse for new projectsFound in older code
    Recommended: Always use 'let' for variable declarations in modern JavaScript development.

    Strings

    Understanding how JavaScript interprets quoted and unquoted text is fundamental to avoiding common programming errors. Let's explore this concept through practical examples.

    1. In your code editor, add single quotes around myMessage in the alert, as shown below:

      alert('myMessage');
    2. Save and reload the page in the browser.

      The alert now literally displays myMessage because the quotes instruct JavaScript to treat those characters as literal text rather than as a variable reference. This demonstrates the critical difference between variable names and string literals.

      Click OK to close the alert.

      JavaScript Syntax Essentials

      Strings

      Text data enclosed in single or double quotes. Quotes tell JavaScript to treat the content as literal characters rather than code.

      Quotes

      Either single or double quotes work for strings. Issues arise with nested quotes, so choose consistently throughout your code.

      Semi-colons

      Indicate the end of a JavaScript statement. Optional at line endings but recommended for clarity and best practices.

      Addition vs Concatenation

      FeatureNumbersStrings
      OperationMathematical additionString concatenation
      Example Code2 + 2'2' + '2'
      Result422
      Plus Sign RoleAddition operatorConcatenation operator
      Recommended: Remember that quotes determine whether the plus sign adds numbers or joins strings together.

    Strings, Quotes, & Semi-Colons

    String: A data type that stores text. In JavaScript, string values must be enclosed in quotes (either single or double). Both the alert() and log() methods accept strings as arguments.

    Quotes instruct JavaScript to interpret text literally as a string of characters. Without quotes, JavaScript interprets the characters as a variable name or other code element.

    Single vs. double quotes: Both are functionally equivalent in JavaScript, though consistency within a project is important. Issues can arise with nested quotes, so choose your quote style based on your content needs.

    Semi-colons ; mark the end of a JavaScript statement. While technically optional at line endings due to Automatic Semicolon Insertion (ASI), explicit semicolons are considered best practice for code clarity and preventing potential parsing issues.

  • Switch back to your code editor.
  • Rather than deleting this instructional code, we'll preserve it for reference by commenting it out. Add double slashes // to the beginning of each line:

    // let myMessage = 'Hello';
    // alert('myMessage');
    // console.log('Hello from console');

    TIP: Most modern code editors support rapid commenting. Select the lines and press Cmd–/ (Mac) or Ctrl–/ (Windows). This shortcut also works on single lines when your cursor is positioned anywhere within the line.

  • Save and reload the page in the browser.

    Nothing executes because all the code is now commented out and ignored by the JavaScript interpreter.

  • JavaScript Syntax Essentials

    Strings

    Text data enclosed in single or double quotes. Quotes tell JavaScript to treat the content as literal characters rather than code.

    Quotes

    Either single or double quotes work for strings. Issues arise with nested quotes, so choose consistently throughout your code.

    Semi-colons

    Indicate the end of a JavaScript statement. Optional at line endings but recommended for clarity and best practices.

    Comments

    Comments are explanatory notes within code that document functionality and provide context for other developers (including your future self). Comments are completely ignored during code execution and have no impact on program performance. Single-line comments begin with a double-slash: //

    Commenting out refers to temporarily disabling code by converting it to comments. This technique allows you to preserve code for future reference or testing without deleting it permanently—a valuable debugging and development strategy.

    Code Comments

    Pros
    Explain complex code logic
    Temporarily disable code without deleting
    Leave notes for future reference
    Help other developers understand your code
    Cons
    Can become outdated if not maintained
    Excessive commenting clutters code
    Should not explain obvious operations

    Strings Vs. Numbers & Concatenation

    One of JavaScript's most important concepts is understanding how data types affect operations. The same operator can behave differently depending on whether it's working with numbers or strings.

    1. Switch back to your code editor.
    2. Let's explore how quotes fundamentally change JavaScript's interpretation of data. Below the commented lines, add the following bold code:

      // console.log('Hello from console');
         alert( 2 + 2 );
         alert( '2' + '2' );
      </script>
    3. Save and reload the page in the browser.

      • The first alert performs mathematical addition, displaying 4. Without quotes, JavaScript treats the values as numbers and the plus sign as an addition operator. Click OK to proceed to the second alert.

      • The second alert demonstrates string concatenation, showing 22. The quotes convert the numbers to strings, and the plus sign now joins them together rather than adding them mathematically.

        Concatenation means connecting or joining elements together. In JavaScript, strings and variables are concatenated into larger strings using the plus operator (+)—a fundamental technique for building dynamic text content.

    4. Click OK to close the alert.
    5. Back in your code editor, delete everything inside the script tag to start fresh.
    6. Create a practical example of string concatenation by declaring two string variables and combining them:

      <script>
         let firstName = 'Dan';
         let lastName = 'Rodney';
         console.log('firstName' + 'lastName');
      </script>
    7. Save and reload the page in the browser.

      In the Console (which should still be open from earlier), you'll see firstNamelastName—the literal concatenation of the quoted strings, not the variable values. This demonstrates why understanding quotes is crucial.

    8. Back in your code editor, remove the quotes around the variable names in the console.log():

      <script>
         let firstName = 'Dan';
         let lastName = 'Rodney';
         console.log(firstName + lastName);
      </script>
    9. Save and reload the browser.
    10. The Console now displays DanRodney—the actual variable values concatenated together. Without quotes, JavaScript correctly interprets firstName and lastName as variable references.

      To improve readability, let's add proper spacing by concatenating a space character between the names.

    11. Back in your code editor, insert a space string between the variables:

      console.log(firstName + ' ' + lastName);

      NOTE: Spaces outside quotes are ignored by JavaScript, but spaces inside quotes become part of the string content!

    12. Save, reload the browser, and check the Console.

      You should now see properly formatted output: Dan Rodney

    13. Let's expand this example by incorporating a numeric variable into our string concatenation:

      <script>
        let firstName = 'Dan';
        let lastName = 'Rodney';
        let highScore = 1200;
        console.log(firstName + ' ' + lastName + ' your high score is ' + highScore);
      </script>

      NOTE: JavaScript handles two primary number types: integers (whole numbers like 1200) and floats (decimal numbers like 1200.5). Both can be concatenated with strings seamlessly.

    14. Save, reload the browser, and check the Console.

      You should see the complete personalized message: Dan Rodney your high score is 1200

    Addition vs Concatenation

    FeatureNumbersStrings
    OperationMathematical additionString concatenation
    Example Code2 + 2'2' + '2'
    Result422
    Plus Sign RoleAddition operatorConcatenation operator
    Recommended: Remember that quotes determine whether the plus sign adds numbers or joins strings together.

    Booleans & Multiple Arguments for Console.log()

    Boolean variables represent one of programming's most fundamental concepts: binary true/false states. A boolean can only hold two possible values: true or false (both must be lowercase in JavaScript). Booleans are essential for conditional logic, decision-making processes, and flow control that you'll encounter throughout your JavaScript journey.

    1. Back in your code editor, declare a boolean variable and demonstrate the console.log method's ability to handle multiple arguments:

      console.log(firstName + ' ' + lastName + ' your high score is ' + highScore);
      
        let online = true;
        console.log('Is Online:', online);
      </script>

      NOTE: The console.log method accepts multiple arguments separated by commas, making it exceptionally useful for debugging and data inspection. In this example, we're logging a descriptive string 'Is Online:' followed by our boolean variable's value. This labeling technique helps identify variables and their values in the Console output—a critical debugging skill.

    2. Save, reload the browser, and check the Console.

      You should now see two distinct lines of output. The second line should read Is Online: true, demonstrating how multiple arguments create clean, labeled output.

    Boolean Values

    Boolean variables store only true or false values (lowercase required). These are essential for conditional logic and decision-making in your programs.

    Error Messages

    Error handling is an integral part of professional JavaScript development. Unlike HTML and CSS, which gracefully ignore errors and continue processing, JavaScript halts execution when it encounters problems. Understanding error messages and debugging techniques is crucial for efficient development workflows.

    The "not defined" error is among the most common you'll encounter—it appears when you attempt to access a variable that doesn't exist, often due to spelling mistakes or scope issues.

    1. Back in your code editor, let's intentionally create an error to understand how JavaScript responds. At the start of the script tag, declare a variable and then misspell it in the console.log:

      <script>
         let veg = 'kale';
         console.log(vex);
      
         let firstName = 'Dan';
    2. Save, reload the browser, and examine the Console.

      • You should see this error: Uncaught ReferenceError: vex is not defined.

      • Notice that none of the subsequent JavaScript executes! This demonstrates JavaScript's "fail-fast" approach—when an error occurs, execution stops immediately to prevent cascading problems.

      • Look for the file name and line number information displayed to the right of the error message. This crucial debugging information helps you locate and fix problems quickly in larger codebases.

    3. Let's explore another common syntax error. In your code editor, remove the equals sign from the variable declaration:

      let veg 'kale';
      console.log(vex);
    4. Save, reload the browser, and check the Console.

      You should see: Uncaught SyntaxError: Unexpected string

      This error occurs because 'kale' is a string literal, but JavaScript doesn't expect a string immediately after a variable name. The missing equals sign breaks the assignment syntax that JavaScript expects.

    5. Back in your code editor, restore the equals sign and correct the variable name in the console.log:

      let veg = 'kale';
      console.log(veg);
    6. Let's examine one more common syntax error by removing the opening parenthesis from the log method:

      let veg = 'kale';
      console.logveg);
    7. Save, reload the browser, and check the Console.

      You should see: Uncaught SyntaxError: Unexpected token ')'

      JavaScript interprets logveg as invalid syntax, but the error doesn't trigger until it encounters the unexpected closing parenthesis ). This demonstrates how syntax errors can sometimes point to locations after the actual problem.

    8. Back in your code editor, restore the opening parenthesis to fix the syntax:

      let veg = 'kale';
      console.log(veg);
    9. Save, reload the browser, and verify the Console.

      The first line should now correctly display kale, confirming that our error handling and debugging process was successful.

    10. You can now close the browser page. While these examples may appear basic, they establish the critical foundation for the sophisticated scripts and applications you'll develop as you advance in JavaScript.

      NOTE: Each exercise in this tutorial includes completed reference code in the Done-Files folder. Navigate to Desktop > Class Files > JavaScript Class > Done-Files > JavaScript-Fundamentals to review the final code implementation and compare it with your work.

    Common JavaScript Errors

    ReferenceError: not defined

    Occurs when you misspell a variable name or try to use a variable that doesn't exist. Check spelling and variable declarations.

    SyntaxError: Unexpected string

    Happens when JavaScript encounters text where it expects different syntax, like missing operators or incorrect punctuation.

    SyntaxError: Unexpected token

    Indicates incorrect syntax structure, such as missing parentheses, brackets, or other required punctuation marks.

    JavaScript Error Behavior

    Unlike HTML and CSS which continue running despite errors, JavaScript stops executing completely when it encounters an error. Always check the Console for error messages and line numbers.

    Variable Naming Rules

    JavaScript enforces strict rules for variable naming. Violation of these rules results in syntax errors:

    • No spaces allowed: ❌ grand totalgrandTotal

    • Cannot start with numbers: ❌ 1-dayday1

    • Special characters forbidden except $ and _: ❌ big-citybigCity

    • Reserved words prohibited: ❌ consolereportConsole

    Variable Naming Requirements

    0/4

    Variable Naming Best Practices

    While rules must be followed to avoid errors, best practices are recommendations that improve code quality, readability, and maintainability. These practices reflect industry standards adopted by professional development teams.

    For multi-word variable names, use camelCase convention: totalCost (preferred over totalcost or total_cost).

    Additional professional naming conventions:

    • Use ALL_CAPS only for constants—values that never change throughout program execution. MOON_DIAMETER exemplifies a constant, as the moon's diameter remains fixed.

    • Balance brevity with clarity in variable names:

      let z = 10016; (too cryptic)

      let fiveDigitZipCode = 10016; (unnecessarily verbose)

      let zipCode = 10016; (clear and concise)

    Variable Naming Examples

    FeaturePoor PracticeBest Practice
    Meaninglesslet z = 10016let zipcode = 10016
    Too VerbosefiveDigitZipCodezipcode
    Case Styletotal_costtotalCost
    ConstantsmoonDiameterMOON_DIAMETER
    Recommended: Use camelCase for variables and UPPER_CASE for constants that never change.

    Key Takeaways

    1JavaScript code must be wrapped in script tags and placed in the HTML head section to function properly on web pages.
    2Methods are actions in JavaScript (like alert and console.log) that accept arguments as data to perform specific tasks.
    3Variables are containers that store values and must be declared with 'let' (preferred) or 'var' before use.
    4Quotes determine whether JavaScript treats content as literal strings or as variable names - quotes create strings, no quotes reference variables.
    5String concatenation uses the plus sign to join text together, while the same operator performs mathematical addition on numbers.
    6JavaScript is case-sensitive, meaning myVar and myvar are completely different variables requiring careful attention to capitalization.
    7Chrome DevTools Console is essential for testing code, viewing output, and debugging JavaScript errors in real-time.
    8When JavaScript encounters an error, it stops executing entirely unlike HTML/CSS, making error detection and fixing crucial for functionality.

    RELATED ARTICLES