JavaScript Syntax

Understand the fundamental rules of JavaScript: statements, semicolons, comments, naming conventions, and strict mode. The building blocks every JS program follows.

Beginner 6 min read 8 examples

Statements

A JavaScript program is a sequence of statements. A statement is a single instruction that the engine executes. Statements end with a semicolon (or are separated by line breaks via ASI).

JavaScript
// Each line below is one statement
let name = "Alice";
let age = 30;
console.log(name);

// Multiple statements on one line (allowed, but avoid)
let x = 1; let y = 2; let z = 3;

// An expression statement - has a value but discarded
name.toUpperCase(); // evaluates to "ALICE" but result is unused

Semicolons and ASI

JavaScript has Automatic Semicolon Insertion (ASI) - the engine adds semicolons in most places where you omit them. However, there are edge cases where ASI gets it wrong:

JavaScript
// This looks like two statements...
const a = 1
const b = 2

// ...but this is a classic ASI trap:
const fn = function() { return "hello" }

// If the next line starts with (, [, or `, ASI may NOT insert:
(function() { console.log("IIFE runs immediately!") })()
// Without semicolons, JS reads: fn()(function(){...})() - TypeError!

// Safe practice: always use semicolons, OR use a linter
Recommendation

Use ESLint with a consistent style (either always semicolons, or never). Do not rely on your memory of ASI rules. Most modern codebases use semicolons - this tutorial uses them throughout.

Comments

Comments are ignored by the JavaScript engine. Use them to explain why, not what:

JavaScript
// Single-line comment - from // to end of line

/*
   Multi-line comment.
   Use for longer explanations.
*/

/**
 * JSDoc comment - for documenting functions.
 * @param {string} name - The user's name
 * @returns {string} A greeting message
 */
function greet(name) {
    return `Hello, ${name}!`;
}

const price = 99.99; // Store price in USD (not cents)
Comment Philosophy

Write comments that explain why something is done, not what - the code itself shows what. A comment like // increment i above i++ adds no value. A comment like // workaround for Safari bug #1234 is invaluable.

Whitespace

JavaScript ignores extra whitespace (spaces, tabs, newlines) between tokens. Use whitespace to make code readable:

JavaScript
// These are identical to the JS engine:
let x=1+2;
let x = 1 + 2;       // readable - prefer this

// Indentation (2 or 4 spaces - be consistent):
function calculate(a, b) {
    const result = a + b;  // 2-space indent (common in JS)
    return result;
}

// Blank lines separate logical sections
const firstName = "Alice";
const lastName = "Smith";

const age = 30;
const city = "London";

Case Sensitivity

JavaScript is case-sensitive. name, Name, and NAME are three different variables:

JavaScript
let name = "alice";
let Name = "Bob";
let NAME = "CHARLIE";

console.log(name);  // alice
console.log(Name);  // Bob
console.log(NAME);  // CHARLIE

// Keywords are lowercase - these throw errors:
// Let x = 1;    // ReferenceError
// CONST y = 2;  // ReferenceError

Identifiers and Naming Conventions

An identifier is the name of a variable, function, class, or label. Rules for valid identifiers:

  • Must start with a letter, $, or _
  • Can contain letters, digits, $, and _
  • Cannot start with a digit
  • Cannot be a reserved keyword
JavaScript
// Valid identifiers
let userName;        // camelCase - variables and functions
let _private;        // underscore prefix (convention: private-ish)
let $element;        // dollar sign (common in jQuery-era code)
let MAX_RETRIES = 3; // SCREAMING_SNAKE_CASE - constants

// Invalid identifiers (SyntaxError):
// let 1user;         // starts with digit
// let user-name;     // hyphen not allowed (use camelCase)
// let class;         // reserved keyword

// Naming conventions in JavaScript:
let userId = 42;                 // camelCase: variables, functions
const API_BASE_URL = "/api/v1";  // SCREAMING_SNAKE_CASE: constants
class UserProfile {}             // PascalCase: classes, constructors
function getUserById() {}        // camelCase: functions

Reserved Words

These words are reserved by the language and cannot be used as identifiers:

break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, false, finally, for, function, if, import, in, instanceof, let, new, null, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with, yield, async, await, of

Strict Mode

"use strict" enables strict mode, which makes JavaScript more predictable by throwing errors for common mistakes instead of silently allowing them.

JavaScript
"use strict"; // Apply to entire script

// Strict mode catches these errors:

// 1. Undeclared variables
// x = 10; // ReferenceError: x is not defined

// 2. Duplicate parameter names
// function add(a, a) {} // SyntaxError

// 3. Deleting variables
// delete myVar; // SyntaxError

// 4. Writing to read-only properties
// undefined = 5; // TypeError

// Can also apply to individual functions:
function myFunc() {
    "use strict";
    // strict mode only inside this function
}
Strict Mode is Automatic in ES Modules

When you use type="module" in your script tag or use import/export, strict mode is enabled automatically. You do not need to write "use strict" explicitly in module files.

Code Blocks

A block is a group of statements enclosed in curly braces { }. Blocks are used with control structures, functions, and classes:

JavaScript
// if block
if (true) {
    console.log("This runs");
    console.log("Both statements are in the block");
}

// function block
function greet(name) {
    const message = `Hello, ${name}!`;
    return message;
}

// Blocks create their own scope for let/const (not var)
{
    let blockScoped = "only visible here";
    const alsoBlockScoped = 42;
    var notBlockScoped = "visible outside too"; // avoid var
}

// console.log(blockScoped); // ReferenceError
console.log(notBlockScoped); // "visible outside too"

Frequently Asked Questions

No - JavaScript has Automatic Semicolon Insertion (ASI) that adds semicolons in most cases. However, relying on ASI can lead to subtle bugs. The safest approach is to either always add semicolons (traditional style) or consistently omit them (Standard JS / no-semicolons style). Pick one and use a linter (ESLint) to enforce it.

"use strict" enables strict mode, which catches common coding mistakes and prevents using unsafe features. It throws errors for: using undeclared variables, deleting variables, duplicate parameters, and other bad practices. Always use strict mode - ES6 modules enable it automatically.

JavaScript uses camelCase for variables and functions (myVariable, getUserName), PascalCase for classes and constructors (UserProfile, HttpClient), and SCREAMING_SNAKE_CASE for constants (MAX_SIZE, API_URL).

Yes - JavaScript identifiers can contain Unicode letters, digits ($, _), and emoji (though emoji names are unusual). The identifier must start with a letter, $, or _. In practice, stick to ASCII letters for readability and cross-team compatibility.