Metronome
JavaScript

JavaScript

Fundamental Syntax Rules in JavaScript

JavaScript's syntax follows specific rules that every developer needs to understand. This section breaks down the core syntax principles that form the foundation of writing clean, error-free JavaScript code.

Statements & Semicolons

In JavaScript, a statement is an instruction that tells the browser to perform a specific action. Each statement typically occupies its own line in your code.

let name = "Alex"    // This is a statement that declares a variable
console.log(name)    // This is a statement that outputs the variable

Semicolon Usage

Semicolons (;) are used to mark the end of a statement:

let age = 25;
console.log(age);

JavaScript has Automatic Semicolon Insertion (ASI), which means semicolons are technically optional in many cases:

let age = 25
console.log(age)  // This works fine without semicolons

Where Semicolons Can Cause Issues If Omitted

When you omit a semicolon at the end of a line, the engine will usually insert one for you but this can cause unexpected behavior when there's certain tokens like (, [, `, +, - or /.

let counter = 10
[1, 2, 3].forEach(num => console.log(num))
// Interpreted as: let counter = 10[1, 2, 3].forEach(...)
// Error: Cannot read properties of undefined (reading 'forEach')

To prevent unexpected behaviors and make your code more readable, it's recommended to always close your statements with ; .

Code Blocks { }

Code blocks are used to group multiple statements together to execute them all as one unit. They are the building blocks of functions, loops, and other control structures.

The curly braces {} mark where a block of code begins and ends.

function greet(name) {
  console.log("Hello, " + name + "!");
}  //Code block of greet function

function farewell(name) {
  console.log("Goodbye, " + name + "!");
} //Code block of farewell function

greet("Alice");    // Hello, Alice!
farewell("Bob");   // Goodbye, Bob!

Code blocks also define block scope, any variables declared with let and const in a code block are only accessible within that block.

{
  let blockScoped = "I'm stuck in here!";
} 

console.log(blockScoped); 
// ReferenceError: blockScoped is not defined

We'll learn more about variables, functions in later sections.

Identifiers (Naming Rules)

An identifier is the name you give to elements in your code, such as variables, constants, functions, classes, and labels. Choosing good, descriptive identifier names is crucial for writing readable and maintainable code.

JavaScript has specific rules for what constitutes a valid identifier name:

  • Starting Character: An identifier must begin with:
    • A letter (a-z or A-Z)
    • An underscore (_)
    • A dollar sign ($)
  • Subsequent Characters: After the first character, an identifier can contain:
    • Letters (a-z, A-Z)
    • Numbers (0-9)
    • Underscores (_)
    • Dollar signs ($)
  • No Reserved Words: Identifiers cannot be any of the JavaScript reserved words (keywords). Explained later in the section.
  • Case Sensitivity: Identifiers are case-sensitive (myVariable is different from myvariable).

Common Naming Conventions:

The following aren't strict rules but good norms to keep in mind:

  • Use camelCase for variables and functions (e.g., orderId, isLoggedIn, calculateSum).
  • Use PascalCase for classes and constructor functions (e.g., OrderItem, HttpRequest, UserProfile).
  • Use UPPER_CASE for constants representing unchanging values (e.g., DEFAULT_TIMEOUT, API_KEY).
  • Dollar sign ($) prefix is often seen when working with DOM elements or libraries like jQuery/RxJS observables. (e.g., $sliderHandle, $navMenu)
// Valid Identifiers
let firstName;
let _internalCounter;
let $elementRef;
let userProfile2;
const API_KEY = "ga-api-atvu891";
function calculateSum() {}
class ProductDetails {}

// Invalid Identifiers
// let 1stPlace;      // Cannot start with a number
// let user-name;     // Hyphen is not allowed
// let const;         // 'const' is a reserved word
// let product#;      // Hash symbol '#' is not allowed

Keywords / Reserved Words

JavaScript has a set of reserved words, often called keywords. These words have special meanings built into the language syntax and are used to perform specific operations or define structures.

You cannot use these reserved words as names (identifiers) for your variables, functions, labels, or classes. Attempting to do so will result in a SyntaxError.

// Correct: Using keywords for their intended purpose
let switch = 10;
if (switch > 5) {
  console.log("Count is greater than 5");
}
// SyntaxError: Unexpected token 'switch'

Some frequently encountered keywords include:

  • let, const, var (for variable declaration)
  • if, else, switch (for conditional logic)
  • for, while, do (for loops)
  • function (for defining functions)
  • return (for exiting functions)
  • class (for defining classes)
  • try, catch, finally, throw (for error handling)
  • import, export (for modules)
  • true, false, null, undefined (primitive values/types, also reserved)
  • this, super, new, delete, typeof, instanceof (operators/special keywords)

Whitespace in JavaScript

JavaScript generally ignores extra spaces, tabs, and line breaks (collectively called "whitespace") outside of strings.

// All of these do exactly the same thing:
let sum=a+b;
let sum = a  +  b;

// Line breaks outside strings are also ignored
let product = 
    price * 
    quantity;  

When Whitespace Matters

  1. Within strings:

    let greeting = "Hello World";  // Space is part of the string
    let greeting = "Hello   World"; // Three spaces - different string
    
  2. In template literals:

    let message = `Hello
    World`;  // Line break is preserved in template literals
    
  3. For readability (best practice):

    // Preferred: Easy to read
    function calculate(a, b) {
        return a + b;
    }
    
    // Avoided: Hard to read
    function calculate(a,b){return a+b;}
    

Comments

Comments allow you to add notes to your code and are completely ignored by the JavaScript engine.

Single-line Comments

Use // for comments that span a single line:

// This is a single-line comment
let score = 100; // You can also add comments at the end of a line

Multi-line Comments

Use /* */ for comments that span multiple lines:

/* This is a multi-line comment
   that spans across several lines
*/

let total = price * quantity;  /* You can also use
                                 multi-line comments
                                 on a single line if needed */

Comments are useful for documentation, explaining complex logic, and even for temporarily disabling code during debugging or development (since the rendering engine ignores comments).

By understanding these syntax concepts, you're ready to move on to fundamental elements of JavaScript like functions, variables and more.

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.