Fundamentals of JavaScript Code

Free JavaScript Tutorial

Learn essential JavaScript methods, the importance of quotes, numbers versus strings, Booleans, error messages, and troubleshooting JavaScript in this comprehensive tutorial.

This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript tutorial:

JavaScript methods (such as alerts and console.log), Variables, Using Chrome’s DevTools: The JavaScript Console, The importance of quotes, Numbers vs. strings, Concatenation, Booleans, Error messages & troubleshooting JavaScript

Exercise Preview

preview fundamentals

JavaScript Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

Before you see real-life examples of how JavaScript is used, you must first learn some foundational concepts and syntax. These core concepts will be important building blocks for more complex scripts.

Getting Started

  1. Launch your code editor (Visual Studio Code, Sublime Text, etc.). If you are in a Noble Desktop class, launch Visual Studio Code.
  2. In your code editor, close any files you may have open.
  3. For this exercise we’ll be working with the JavaScript-Fundamentals folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  4. In your code editor, open index.html from the JavaScript-Fundamentals folder.
  5. Preview index.html in Chrome. (We’re using Chrome because we’ll be using its DevTools.)

    NOTE: If you’re using Visual Studio Code with the open in browser extension installed, hit Option–B (Mac) or Alt–B (Windows) to open the saved HTML document in a browser.

    If you’re using another code editor or don’t have that keystroke set up, you can open the pages from your browser window to preview it. In your browser, hit Cmd–O (Mac) or Ctrl–O (Windows). Navigate to the JavaScript Class folder and then JavaScript-Fundamentals and double–click on index.html.

  6. Notice this is a blank HTML page. We don’t actually need any page content to start learning JavaScript.

  7. Leave this page open in the browser as you work, so you can reload it to see the changes you make in the code.

Adding JavaScript to a Webpage

JavaScript code needs to be wrapped in a script tag, which we’ll put in the head section.

  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 dialog containing the data in the parentheses. Methods can be thought of as the verbs of JavaScript.

    Methods & Arguments

    methods are actions, they do things. The action performed by the alert() method is to open a dialog. Methods are written as methodName followed by parentheses, into which option(s) called arguments are often passed.

    Code format: method(argument)

    arguments are the data passed into the parentheses of a method. In the alert() method above, the argument is 'Hello'

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

    You should see a dialog that says Hello. Notice that it does not have quotes, even though there were quotes in the code. We’ll explain that more in a moment.

    Click OK to close the alert.

The Console

The Console is a browser developer tool used for testing code and debugging. Let’s output our greeting to the Console using the log() method on JavaScript’s console object.

  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 opens, but how do we see the message we logged to the Console?

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

    Here you should see the message Hello from console

Variables

A variable is a container that stores a value. In JavaScript, variables (vars) need to be declared (created) and assigned a value. Variables are declared using the reserved word let or var, although let is the preferred, more modern syntax.

JavaScript is case-sensitive, so pay close attention to typing variable names correctly: myvar, myVar, Myvar, myVar, and MYVAR are all different variables!

  1. Switch back to your code editor.
  2. Make the following changes shown in bold. Pay close attention to capitalization, because JavaScript is case-sensitive!

    <script>
       let myMessage = 'Hello';
       alert(myMessage);
       console.log('Hello from console');
    </script>
    
    Let’s break this code down:
    • We made up a variable named myMessage into which we store the text 'Hello'
    • The let before the variable name says we’re declaring (creating) a new variable.
    • The alert is then told to display the contents of that variable. Notice we no longer have quotes around text inside the alert() method.
  3. Save and reload the page in the browser.

    • In the alert, you should see the same Hello message, but this time it’s getting that from the value of the myMessage variable.
    • Click OK to close the alert.

Strings

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

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

    The alert should literally say myMessage because the quotes in our code say to take those characters literally. We got the variable’s name, instead of its value.

    Click OK to close the alert.

    Strings, Quotes, & Semi-Colons

    string A variable that stores text is called a string. The text goes in quotes, either single or double (both okay). The alert() and log() methods are both taking strings as their arguments.

    quotes tell JavaScript that text should be read literally as a string of characters. If there are no quotes, the characters are seen as a variable.

    single or double quotes: either are fine, although issues can arise when there are quotes inside quotes (nested quotes).

    semi-colons ; indicate the end of a statement. Semi-colons are optional when used at the end of a line, but we will be using them.

  3. Switch back to your code editor.
  4. We don’t need this code anymore, because we’re moving on to something else. We’d like to keep the code for reference though. Add a double slash // to each line to comment out the code.

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

    TIP: To quickly comment out code, select the lines and hit Cmd–/ (Mac) or Ctrl–/ (Windows). You can also click anywhere into a single line and use the same keystroke to comment out that line.

  5. Save and reload the page in the browser.

    Nothing will happen because all the code is ignored.

Comments

Comments are notes in the code that explain what the code is doing. Comments are ignored at run time and have no effect on the program. Single line comments are preceded by a double-slash: //

Commenting out refers to deactivating code by putting it in a comment. A reason to comment out (rather than delete) code is so you can reactivate or refer to it later.

Strings vs. Numbers & Concatenation

  1. Switch back to your code editor.
  2. Let’s further explore how quotes work. 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 is doing basic math, so you should see 4. The plus is working as an addition sign. Click OK to see a second alert.

    • The second alert is doing something different. Quotes indicate a string (characters). The plus sign is now putting one string of characters after another, a process called concatenation.

      Concatenation means to connect or join together. Substrings and variables are concatenated into larger strings using the plus sign (+).

  4. Click OK to close the alert.
  5. Back in your code editor, delete everything inside the script tag.
  6. As shown below, declare two string variables followed by a concatenation line:

    <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) it should say firstNamelastName

    The quotes in our code treat those words as strings (or literal characters). We’ve concatenated (combined) the two strings, but that’s not what we want.

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

    <script>
       let firstName = 'Dan';
       let lastName = 'Rodney';
       console.log(firstName + lastName);
    </script>
    
  9. Save and reload the browser.
  10. In the Console you should see the message we wanted in the first place: DanRodney

    Without quotes, JavaScript treats firstName and lastName as the variables they are.

    To make this better, let’s concatenate a space between the first and last name.

  11. Back in your code editor, add the following ' space ' space + shown in bold:

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

    NOTE: Spaces outside the quotes don’t matter, but spaces inside the quotes do!

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

    You should now see the names separated by a space: Dan Rodney

  13. Back in your code editor, declare a new number variable, and then concatenate it into the greeting:

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

    NOTE: Number values can be either integers (whole numbers) or floats (decimals).

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

    You should get the greeting: Dan Rodney your high score is 1200

Booleans & Multiple Arguments for console.log()

A boolean variable has a value of either true of false (which need to be lowercase). Booleans are used a lot in conditional logic, which you’ll get to later.

  1. Back in your code editor, declare a new boolean variable, and add a new console.log:

      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, each separated by a comma. This is very useful for identifying or labeling output. In the code above, we log a string 'Is Online:' followed by the value of our new online variable. This will remind us in the Console of which variable the value goes with.

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

    You should now see two lines, the second (new) line should say Is Online: true

Error Messages

You’ll be getting a lot of error messages during your coding journey, which is normal! Let’s see some errors and how to troubleshoot our code.

not defined is an error you’ll see if you spell a variable wrong or otherwise attempt to access a variable that does not exist.

  1. Back in your code editor, at the start of the script tag, declare a new 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 check the Console.

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

    • Notice that none of the other JavaScript runs! Unlike HTML and CSS which are very forgiving and continue on, when JavaScript encounters an error it stops.

    • To the far right of the error, notice it lists the file name and line number (so you can find the error in your code).

  3. Back in your code editor, delete the equal sign from the variable declaration:

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

    You should see this error: Uncaught SyntaxError: Unexpected string

    This is because 'kale' is a string, but a string was not expected immediately following the variable name. What is expected is the equal sign.

  5. Back in your code editor, put the equal sign back and fix the veg spelling in the console.log:

    let veg = 'kale';
    console.log(veg);
    
  6. Introduce a new error by removing the opening parentheses from log:

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

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

    logveg is not valid syntax, but the error didn’t kick in until ).

  8. Back in your code editor, put the opening parentheses back so the code is correct:

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

    The first line in the Console should say kale

  10. We’re done, so you can close the page in your web browser.

    These examples may seem basic, but they are laying a very important foundation for the more complex scripts you’ll soon be writing.

    NOTE: For each exercise in this book, we have the completed code in a folder named Done-Files. Go to Desktop > Class Files > JavaScript Class > Done-Files > JavaScript-Fundamentals if you want to refer to our final code.

Variable Naming Rules

When naming variables keep the following rules in mind:

  • Do not use spaces:
    bad: grand total
    good: grandTotal

  • Do not start with a number:
    bad: 1day
    good: day1

  • Do not use special characters except for $ and _
    bad: big-city
    good: bigCity

  • Do not use reserved words:
    bad: console
    good: reportConsole

Variable Naming Best Practices

Rules (like those above) must be followed or else you get an error. Best practices are optional, but recommended. Disregarding a best practice won’t affect your code’s performance.

If a variable name consists of more than one word, a best practice is to write it in camelCase like totalCost (instead of totalcost or total_cost).

More best practices for naming variables:

  • The only names that get uppercased are constants, which means their value never changes. MOON_DIAMETER would be an example of a constant, because the moon’s diameter never varies.

  • Make variable names short, yet meaningful:

    let z = 10016; lacks meaning, because it’s too short.

    let fiveDigitZipCode = 10016; is meaningful, but needlessly long.

    let zipcode = 10016; is meaningful, and short.

How to Learn JavaScript

Master JavaScript with hands-on training. JavaScript is one of the world's most widely-used coding languages. Learn JavaScript and its libraries to start creating interactive websites and mobile apps.

Yelp Facebook LinkedIn YouTube Twitter Instagram