JavaScript - Syntax

Overview

Estimated time: 15–25 minutes

JavaScript uses C-like syntax: statements, braces for blocks, and functions. Semicolons are optional (ASI) but can prevent edge cases.

Learning Objectives

  • Write statements and blocks with consistent semicolons.
  • Use valid identifiers and common literal forms.
  • Apply single-line and multi-line comments.

Prerequisites

Statements and Blocks

{
  const x = 2;
  const y = 3;
  console.log(x + y);
}

Semicolons

ASI adds semicolons in many cases, but not all (e.g., lines starting with (, [, /, +, -). Prefer explicit semicolons to avoid pitfalls.

Identifiers and Literals

  • Identifiers are case-sensitive; use camelCase for variables/functions, PascalCase for classes.
  • Literals: numbers (42, 0b1010, 0xFF, 1_000_000), strings ('x', "x", `x`), booleans, null, undefined, arrays, objects.

Comments

// single-line
/* multi-line */

Example

// Compute average
const scores = [90, 85, 95];
const avg = scores.reduce((a,b) => a + b, 0) / scores.length;
console.log('Average:', avg);

Checks for Understanding

  1. When can automatic semicolon insertion (ASI) fail?
  2. What casing is idiomatic for variable and class names?
Show answers
  1. At lines that begin with tokens like (, [, /, +, -; also with return statements followed by a newline.
  2. camelCase for variables/functions; PascalCase for classes.

Exercises

  1. Rewrite the example to include explicit semicolons on each statement.
  2. Create a function named sumThree that returns the sum of three numbers and logs the result.