javascript

1.2 JavaScript Syntax

Master the complete JavaScript syntax — statements, expressions, variables, operators, comments, semicolons, case sensitivity, whitespace, and the rules that govern how valid JavaScript is written.

22 min read 20 sections Tutorial
Share

JavaScript Syntax

JavaScript Syntax

Syntax is the set of rules that defines how a valid JavaScript program is written. Just like English has grammar rules — sentences need a subject and verb, punctuation ends sentences — JavaScript has its own rules about how code must be structured for the engine to understand it.

Breaking syntax rules causes a SyntaxError and your program won't run at all. This page covers every fundamental syntax rule you need to write correct JavaScript.

Syntax vs Logic

Syntax errors are caught immediately — your code won't run at all. Example: forgetting a closing }.

Logic errors are silent — code runs but produces wrong results. Example: using + instead of - in a calculation.

Master syntax first so you can focus on logic.

📝

Statements

Instructions that perform an action. Each statement typically ends with a semicolon.

💬

Comments

Notes in the code ignored by the engine. Single-line // and multi-line /* */.

🔡

Case Sensitivity

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

Whitespace

Spaces, tabs, and newlines are ignored by the engine. Use them freely for readability.

Statements

Statements

A JavaScript program is a sequence of statements. A statement is a complete instruction — it tells the engine to do something. Statements are executed one after another, from top to bottom.

javascript
1// Each line below is a statement
2let name = 'Alice'; // declaration statement
3name = 'Bob'; // assignment statement
4console.log(name); // expression statement
5
6if (name === 'Bob') { // if statement (block)
7 console.log('Hello Bob!');
8}
9
10for (let i = 0; i < 3; i++) { // for statement (block)
11 console.log(i);
12}
13
14// Multiple statements can be on one line (not recommended)
15let x = 1; let y = 2; console.log(x + y);
16
17// A block { } groups multiple statements together
18{
19 let temp = 10;
20 console.log(temp);
21}

One Statement Per Line

While JavaScript allows multiple statements on one line (separated by ;), always write one statement per line. It is far easier to read, debug, and maintain. Code is read far more often than it is written.

Semicolons

Semicolons

In JavaScript, semicolons ; mark the end of a statement. They are technically optional in most cases because JavaScript has Automatic Semicolon Insertion (ASI) — the engine inserts them for you when it thinks a statement ends.

However, relying on ASI can lead to subtle, hard-to-spot bugs.

javascript
1// ✅ With semicolons — explicit, clear, no surprises
2const a = 5;
3const b = 10;
4console.log(a + b);
5
6// ✅ Without semicolons — works fine (ASI inserts them)
7const c = 5
8const d = 10
9console.log(c + d)
10
11// ❌ ASI FAILURE — classic bug
12// You might expect: const x = 1; [1, 2, 3].forEach(...)
13// JS reads it as: const x = 1[1, 2, 3].forEach(...) → TypeError!
14const arr = [1, 2, 3]
15;[1, 2, 3].forEach(n => console.log(n)) // workaround: leading semicolon
16
17// ❌ Another ASI trap with return
18function getValue() {
19 return // ASI inserts ; here!
20 { // this object is never returned
21 value: 42
22 }
23}
24console.log(getValue()); // undefined — not { value: 42 }!

Always use semicolons — or always omit them (consistently)

The JavaScript community is split: some style guides (Airbnb) require semicolons, others (Standard JS) forbid them. Either approach is fine — but be consistent within a project. Use Prettier to enforce it automatically so you never have to think about it.

Comments

Comments

Comments are notes written in the code for humans — the JavaScript engine completely ignores them. Use comments to explain why something is done (not what — the code itself shows what).

javascript
1// This is a single-line comment — everything after // is ignored
2console.log('Single-line comment above me');
3
4/*
5 This is a multi-line comment.
6 It can span as many lines as you need.
7 Useful for longer explanations or temporary code blocks.
8*/
9console.log('Multi-line comment above me');
10
11// Inline comment — after valid code
12const TAX_RATE = 0.18; // 18% GST — update if rate changes
13
14// ✅ Good comment — explains WHY, not WHAT
15const delay = 300; // Debounce delay in ms — prevents API spam on keypress
16
17// ❌ Bad comment — just repeats the code
18const price = 99; // set price to 99
19
20// Commenting out code temporarily (use sparingly)
21// console.log('debug: checking value here');
22console.log('All comments above are ignored by the engine');
Pro Tips
  • 1Comment the why, not the what. // increment i is useless — the code already says that. // offset by 1 because array is 1-indexed is useful.
  • 2Don't leave large blocks of commented-out code in production. Use version control (git) to recover old code instead.
  • 3Use // TODO: and // FIXME: comments to flag things to come back to. Most editors highlight these specially.

Case Sensitivity

Case Sensitivity

JavaScript is completely case-sensitive. Every identifier — variable names, function names, keywords — must match exactly in case. let is a keyword; Let and LET are not.

javascript
1// ✅ These are THREE different variables
2let color = 'red';
3let Color = 'green';
4let COLOR = 'blue';
5console.log(color, Color, COLOR); // red green blue
6
7// ✅ Keywords must be lowercase
8let x = 1; // ✅ correct
9// Let x = 1; // ❌ SyntaxError — 'Let' is not a keyword
10// LET x = 1; // ❌ SyntaxError
11
12// ✅ Built-in objects are case-sensitive too
13console.log(typeof Math.PI); // 'number' ✅
14// console.log(math.PI); // ❌ ReferenceError: math is not defined
15// console.log(Math.pi); // ❌ undefined — 'pi' not 'PI'
16
17// ✅ Function names are case-sensitive
18function greet() { return 'hello'; }
19// greet() ✅ Greet() ❌ GREET() ❌
20console.log(greet());
21
22// ✅ HTML attributes are NOT case-sensitive, but JS is
23// onclick vs onClick vs ONCLICK — all work in HTML
24// but in JavaScript: element.onclick (all lowercase)

Common Case Mistakes

  • console.Log()ReferenceError (should be console.log)
  • document.GetElementById()TypeError (should be getElementById)
  • Math.floor() → ✅ correct
  • math.floor()ReferenceError (should be Math with capital M)
  • Let, Const, Var → all SyntaxError (must be lowercase)

Identifiers — Naming Rules

Identifiers — Naming Rules

An identifier is a name you give to a variable, function, class, or label. JavaScript has strict rules about what characters are valid in an identifier.

RuleValid ExamplesInvalid Examples
Must start with a letter, _ or $name, _count, $price1name, -value, @tag
Can contain letters, digits, _ or $user1, total_price, $eluser-name, my value, rate%
Cannot be a reserved keywordlet, myLet, letMelet, const, for, if, class
Case-sensitiveuserName, UserName (two names)
No spaces allowedfirstName, first_namefirst name
javascript
1// ✅ Valid identifiers
2let name = 'Alice';
3let userName = 'bob123';
4let _private = 'hidden'; // underscore prefix = convention for private
5let $element = null; // $ prefix = common in jQuery / DOM libs
6let camelCase = true;
7let CONSTANT = 3.14; // all-caps = convention for constants
8let _123 = 'valid'; // digits allowed after first char
9
10// ❌ Invalid identifiers (would cause SyntaxError)
11// let 1name = 'bad'; // starts with a number
12// let my-var = 'bad'; // hyphens not allowed
13// let my var = 'bad'; // spaces not allowed
14// let for = 'bad'; // reserved keyword
15// let class = 'bad'; // reserved keyword
16
17console.log(name, userName, _private, $element);
18console.log(CONSTANT);

Whitespace

Whitespace

Whitespace — spaces, tabs, and newlines — is ignored by the JavaScript engine (outside of strings). This means you can format your code however you like for readability. The engine only cares about the tokens, not the space between them.

javascript
1// These are all identical to the JavaScript engine:
2console.log(1 + 2);
3console.log(1+2);
4console.log( 1 + 2 );
5console.log(
6 1 +
7 2
8);
9
10// ✅ Use whitespace to make code readable
11const result = (10 + 5) * 2 / 3;
12
13// ❌ Technically valid but unreadable
14const result2=(10+5)*2/3;
15
16// Whitespace INSIDE strings IS significant
17console.log('hello world'); // 'hello world' — space preserved
18console.log('hello world'); // 'hello world' — two spaces preserved
19
20console.log(result, result2); // both equal 10

Let Prettier handle formatting

Never manually debate spaces vs tabs or brace placement. Install Prettier in VS Code and it auto-formats on every save. Your code will always be consistently formatted with zero effort.

Expressions vs Statements

Expressions vs Statements

Two fundamental building blocks of JavaScript syntax are expressions and statements. Understanding the difference explains many syntax rules.

Expression
Produces a VALUE.
Can be used wherever
a value is expected.
Examples:
5 + 3 → 8
'hello' → 'hello'
true → true
x * 2 → (some number)
Math.random() → (0–1)
a > b → true/false
x = 5 → 5 (assignment
is also expr)
[1, 2, 3] → array
{ a: 1 } → object
() => x + 1 → function
VS
Statement
Performs an ACTION.
Does NOT produce a value
you can use inline.
Examples:
let x = 5; (declaration)
if (x > 0) { } (conditional)
for (;;) { } (loop)
while (true) { } (loop)
return value; (return)
throw new Error(); (throw)
import './app.js'; (import)
function fn() { } (declaration)
Statements contain
expressions inside them.
javascript
1// Statements — perform actions
2let x = 10; // declaration statement
3if (x > 5) { console.log('big'); } // if statement
4for (let i = 0; i < 2; i++) {} // for statement
5
6// Expressions — produce values (usable inline)
7const a = 5 + 3; // 5 + 3 is an expression → value 8
8const b = x > 5 ? 'big' : 'small'; // ternary expression → string
9const c = Math.max(1, 2, 3); // function call expression → 3
10const d = [1, 2, 3].length; // property access expression → 3
11
12console.log(a, b, c, d);
13
14// Expression statement — an expression used as a statement
15console.log('hello'); // function call (expression) used as a statement
16x++; // increment (expression) used as a statement
17
18// Can't use a statement where an expression is expected:
19// const val = if (true) { 5 }; // ❌ SyntaxError — if is a statement
20const val = true ? 5 : 0; // ✅ ternary is an expression
21console.log(val);

Code Blocks

Code Blocks { }

A block is a group of zero or more statements enclosed in curly braces { }. Blocks are used with control flow statements (if, for, while) and function definitions to group statements that belong together.

javascript
1// Block with if
2if (true) {
3 console.log('Line 1 of block');
4 console.log('Line 2 of block');
5} // end of block
6
7// Block with for
8for (let i = 0; i < 3; i++) {
9 const msg = `iteration ${i}`; // block-scoped variable
10 console.log(msg);
11}
12// console.log(msg); // ❌ ReferenceError — 'msg' is scoped to the for block
13
14// Block with function
15function add(a, b) {
16 const result = a + b; // scoped to this block
17 return result;
18}
19console.log(add(3, 4));
20
21// Standalone block (rarely used, but valid)
22{
23 const temp = 'only in this block';
24 console.log(temp); // ✅
25}
26// console.log(temp); // ❌ ReferenceError — out of scope
27
28// Single-line if WITHOUT block — valid but risky
29if (true) console.log('no braces — only one statement allowed');
30// Recommendation: always use braces, even for single statements

Always use braces

Even when an if or loop has only one statement, always include the { }. Without braces, adding a second line to the block later silently creates a bug — the second line runs regardless of the condition. Most style guides enforce braces.

Values & Literals

Values & Literals

A literal is a fixed value written directly in the code. Every literal has a type that determines what operations you can perform on it.

javascript
1// Number literals
2console.log(42); // integer
3console.log(3.14); // decimal (float)
4console.log(-7); // negative
5console.log(1_000_000); // numeric separator (ES2021) — same as 1000000
6console.log(0xFF); // hexadecimal — 255
7console.log(0b1010); // binary — 10
8console.log(0o17); // octal — 15
9console.log(2e6); // scientific notation — 2000000
10
11// String literals
12console.log('single quotes');
13console.log("double quotes");
14console.log(`template literal — can span
15multiple lines`);
16console.log(`Hello ${'World'}!`); // template with expression
17
18// Boolean literals
19console.log(true);
20console.log(false);
21
22// Null & Undefined literals
23console.log(null); // intentional absence of value
24console.log(undefined); // variable declared but not assigned
25
26// Array literal
27console.log([1, 'two', true, null]);
28
29// Object literal
30console.log({ name: 'Alice', age: 25 });
31
32// RegExp literal
33console.log(/^[a-z]+$/i); // regular expression
34
35// BigInt literal (ES2020)
36console.log(9007199254740993n); // n suffix = BigInt

Operators

Operators

Operators are symbols that perform operations on values (operands). JavaScript has a rich set of operators for arithmetic, comparison, logic, assignment, and more.

javascript
1// ── Arithmetic operators ─────────────────────────────────
2console.log(10 + 3); // 13 — addition
3console.log(10 - 3); // 7 — subtraction
4console.log(10 * 3); // 30 — multiplication
5console.log(10 / 3); // 3.3… — division
6console.log(10 % 3); // 1 — modulus (remainder)
7console.log(10 ** 3); // 1000 — exponentiation (ES2016)
8
9let n = 5;
10n++; console.log(n); // 6 — post-increment
11++n; console.log(n); // 7 — pre-increment
12n--; console.log(n); // 6 — post-decrement
13
14// ── Assignment operators ──────────────────────────────────
15let x = 10; // assign
16x += 5; console.log(x); // 15 — x = x + 5
17x -= 3; console.log(x); // 12 — x = x - 3
18x *= 2; console.log(x); // 24 — x = x * 2
19x /= 4; console.log(x); // 6 — x = x / 4
20x %= 4; console.log(x); // 2 — x = x % 4
21x **= 3; console.log(x); // 8 — x = x ** 3
22
23// ── Comparison operators ──────────────────────────────────
24console.log(5 == '5'); // true — loose (type coercion)
25console.log(5 === '5'); // false — strict (no coercion) ← always use this
26console.log(5 != '5'); // false — loose not-equal
27console.log(5 !== '5'); // true — strict not-equal ← always use this
28console.log(5 > 3); // true
29console.log(5 < 3); // false
30console.log(5 >= 5); // true
31console.log(5 <= 4); // false
32
33// ── Logical operators ─────────────────────────────────────
34console.log(true && false); // false — AND
35console.log(true || false); // true — OR
36console.log(!true); // false — NOT
37
38// ── String operator ───────────────────────────────────────
39console.log('Hello' + ' ' + 'World'); // 'Hello World' — concatenation
40
41// ── Ternary operator ──────────────────────────────────────
42const age = 20;
43const status = age >= 18 ? 'adult' : 'minor';
44console.log(status); // 'adult'
45
46// ── typeof operator ───────────────────────────────────────
47console.log(typeof 42); // 'number'
48console.log(typeof 'hello'); // 'string'
49console.log(typeof true); // 'boolean'
50console.log(typeof undefined); // 'undefined'
51console.log(typeof null); // 'object' ← famous bug
52console.log(typeof {}); // 'object'
53console.log(typeof []); // 'object'
54console.log(typeof function(){}); // 'function'

String Syntax

String Syntax

Strings can be written with single quotes, double quotes, or backticks. Each has slightly different behaviour.

SyntaxExampleSpecial Feature
Single quotes ' ''Hello World'Standard. Common in JS codebases.
Double quotes " ""Hello World"Same as single quotes. Useful when string contains an apostrophe.
Backticks ` ``Hello ${name}`Template literals — multi-line + embedded expressions via ${}.
javascript
1// Single and double quotes — identical behaviour
2const a = 'Hello';
3const b = "World";
4console.log(a + ' ' + b); // Hello World
5
6// Use the other quote to avoid escaping
7const c = "It's a great day"; // ✅ no escape needed
8const d = 'She said "hello"'; // ✅ no escape needed
9const e = 'It\'s escaped'; // ✅ escaped apostrophe
10
11// Template literals — backticks
12const name = 'Alice';
13const age = 25;
14
15// Embed expressions with ${}
16console.log(`Name: ${name}, Age: ${age}`);
17console.log(`In 10 years: ${age + 10}`);
18console.log(`Is adult: ${age >= 18 ? 'yes' : 'no'}`);
19
20// Multi-line strings — only works with backticks
21const multiLine = `Line 1
22Line 2
23Line 3`;
24console.log(multiLine);
25
26// Escape sequences — work in all three quote styles
27console.log('Tab:\there');
28console.log('Newline:\nhere');
29console.log('Backslash: \\');
30console.log('Unicode: \u2764'); // ❤

Variable Declarations

Variable Declarations

Variables are declared with three keywords: let, const, and var. Each has different scoping and reassignment rules.

javascript
1// ── const — block-scoped, cannot be reassigned ───────────
2const PI = 3.14159;
3console.log(PI);
4// PI = 3; // ❌ TypeError: Assignment to constant variable
5
6// const with objects — the binding is constant, not the object
7const user = { name: 'Alice' };
8user.name = 'Bob'; // ✅ mutating the object is fine
9// user = {}; // ❌ reassigning the binding is not
10console.log(user.name); // 'Bob'
11
12// ── let — block-scoped, can be reassigned ─────────────────
13let score = 0;
14score = 10; // ✅ reassignment allowed
15score += 5;
16console.log(score); // 15
17
18if (true) {
19 let blockVar = 'inside block';
20 console.log(blockVar); // ✅
21}
22// console.log(blockVar); // ❌ ReferenceError — block scoped
23
24// ── var — function-scoped, avoid in modern code ───────────
25var oldStyle = 'legacy';
26console.log(oldStyle);
27
28if (true) {
29 var leaksOut = 'not block scoped!';
30}
31console.log(leaksOut); // ✅ 'not block scoped!' — var ignores blocks!
32
33// var hoisting — can use before declaration (bad)
34console.log(hoisted); // undefined (not an error!)
35var hoisted = 'value';
36console.log(hoisted); // 'value'
KeywordScopeReassignableHoistedUse When
constBlock❌ NoYes (TDZ)Default — use for everything
letBlock✅ YesYes (TDZ)When value needs to change
varFunction✅ YesYes (undefined)Never — legacy code only

Rule: const by default, let when needed, never var

Start every variable with const. Only switch to let if you need to reassign it (loop counters, accumulators, flags). Never use var in new code — its function scope and hoisting behaviour cause confusing bugs.

Function Syntax

Function Syntax

JavaScript has four ways to define a function. All of them create callable blocks of code, but they differ in hoisting behaviour and how they handle this.

javascript
1// ── 1. Function Declaration ───────────────────────────────
2// Hoisted — can be called before it's defined in the file
3function add(a, b) {
4 return a + b;
5}
6console.log(add(2, 3)); // 5
7
8// ── 2. Function Expression ────────────────────────────────
9// Not hoisted — must be defined before calling
10const multiply = function(a, b) {
11 return a * b;
12};
13console.log(multiply(4, 3)); // 12
14
15// ── 3. Arrow Function (ES6) ───────────────────────────────
16// Concise syntax — no own 'this' binding
17const subtract = (a, b) => a - b; // implicit return (one expression)
18const square = x => x * x; // single param — no parens needed
19const greet = () => 'Hello!'; // no params — empty parens needed
20const divide = (a, b) => { // block body — explicit return needed
21 if (b === 0) return 'Cannot divide by zero';
22 return a / b;
23};
24
25console.log(subtract(10, 3)); // 7
26console.log(square(5)); // 25
27console.log(greet()); // 'Hello!'
28console.log(divide(10, 2)); // 5
29
30// ── 4. Method Shorthand (inside objects) ──────────────────
31const calculator = {
32 value: 0,
33 add(n) { this.value += n; return this; }, // method shorthand
34 subtract(n) { this.value -= n; return this; },
35 result() { return this.value; },
36};
37console.log(calculator.add(10).subtract(3).result()); // 7
38
39// ── Default Parameters ────────────────────────────────────
40function createUser(name, role = 'viewer', active = true) {
41 return { name, role, active };
42}
43console.log(createUser('Alice')); // { name:'Alice', role:'viewer', active:true }
44console.log(createUser('Bob', 'admin')); // { name:'Bob', role:'admin', active:true }

Control Flow Syntax

Control Flow Syntax

Control flow statements alter the order of execution — branching with if/else, repeating with loops, or switching between cases.

javascript
1// ── if / else if / else ───────────────────────────────────
2const score = 72;
3
4if (score >= 90) {
5 console.log('A');
6} else if (score >= 80) {
7 console.log('B');
8} else if (score >= 70) {
9 console.log('C');
10} else {
11 console.log('F');
12} // → C
13
14// ── Ternary (shorthand if/else for expressions) ───────────
15const pass = score >= 50 ? 'Pass' : 'Fail';
16console.log(pass); // 'Pass'
17
18// ── switch ────────────────────────────────────────────────
19const day = 'Mon';
20switch (day) {
21 case 'Mon':
22 case 'Tue':
23 case 'Wed':
24 case 'Thu':
25 case 'Fri':
26 console.log('Weekday');
27 break;
28 case 'Sat':
29 case 'Sun':
30 console.log('Weekend');
31 break;
32 default:
33 console.log('Unknown');
34}
35
36// ── for loop ──────────────────────────────────────────────
37for (let i = 0; i < 4; i++) {
38 process.stdout ? process.stdout.write(i + ' ') : console.log(i);
39}
40console.log();
41
42// ── for...of — iterates values (arrays, strings) ──────────
43const fruits = ['apple', 'banana', 'cherry'];
44for (const fruit of fruits) {
45 console.log(fruit);
46}
47
48// ── for...in — iterates keys (object properties) ──────────
49const obj = { a: 1, b: 2, c: 3 };
50for (const key in obj) {
51 console.log(`${key}: ${obj[key]}`);
52}
53
54// ── while ─────────────────────────────────────────────────
55let count = 3;
56while (count > 0) {
57 console.log(`Countdown: ${count}`);
58 count--;
59}
60
61// ── break and continue ────────────────────────────────────
62for (let i = 0; i < 10; i++) {
63 if (i === 3) continue; // skip 3
64 if (i === 6) break; // stop at 6
65 console.log(i); // 0, 1, 2, 4, 5
66}

Error Handling Syntax

Error Handling Syntax

JavaScript uses try...catch...finally to handle runtime errors gracefully instead of crashing the program.

javascript
1// ── try / catch ───────────────────────────────────────────
2try {
3 const result = JSON.parse('{ invalid json }'); // throws SyntaxError
4 console.log(result); // never reached
5} catch (error) {
6 console.log('Caught:', error.message);
7 console.log('Type:', error.constructor.name); // SyntaxError
8}
9
10// ── finally — runs regardless of error ────────────────────
11function fetchData() {
12 try {
13 console.log('Fetching...');
14 throw new Error('Network failure'); // simulate error
15 console.log('Success'); // never runs
16 } catch (err) {
17 console.log('Error:', err.message);
18 } finally {
19 console.log('Cleanup — always runs (close DB, hide loader, etc.)');
20 }
21}
22fetchData();
23
24// ── throw — create your own errors ────────────────────────
25function divide(a, b) {
26 if (b === 0) throw new Error('Cannot divide by zero');
27 if (typeof a !== 'number' || typeof b !== 'number') {
28 throw new TypeError('Both arguments must be numbers');
29 }
30 return a / b;
31}
32
33try {
34 console.log(divide(10, 2)); // 5
35 console.log(divide(10, 0)); // throws
36} catch (e) {
37 console.log('Caught:', e.message);
38}
39
40// Built-in error types
41// TypeError — wrong type
42// RangeError — value out of range
43// SyntaxError — invalid syntax
44// ReferenceError — variable not defined

Module Syntax

Module Syntax — import & export

ES6 introduced a native module system. Modules let you split code into separate files and share only what's needed using export and import.

javascript
1// ── math.js — EXPORTING ───────────────────────────────────
2
3// Named exports — export multiple things
4export const PI = 3.14159;
5
6export function add(a, b) {
7 return a + b;
8}
9
10export function subtract(a, b) {
11 return a - b;
12}
13
14// Default export — one per file
15export default function multiply(a, b) {
16 return a * b;
17}
18
19
20// ── app.js — IMPORTING ────────────────────────────────────
21
22// Import named exports — use exact names in { }
23import { PI, add, subtract } from './math.js';
24
25// Import default export — any name you choose
26import multiply from './math.js';
27
28// Import both at once
29import multiply, { PI, add } from './math.js';
30
31// Import everything as a namespace
32import * as Math from './math.js';
33Math.add(1, 2); // 3
34Math.PI; // 3.14159
35
36// Rename on import
37import { add as sum } from './math.js';
38console.log(sum(3, 4)); // 7
39
40// Dynamic import — load on demand (async)
41async function loadHeavyModule() {
42 const { heavyFunction } = await import('./heavy.js');
43 heavyFunction();
44}

CommonJS vs ES Modules

CommonJS (require / module.exports) is the older Node.js module system still used in many Node projects:

const fs = require('fs');        // CommonJS import
module.exports = { add, PI };    // CommonJS export

ES Modules (import / export) are the modern standard, used in browsers and modern Node.js:

import fs from 'fs';             // ES Module import
export { add, PI };              // ES Module export

New projects should use ES Modules. Add "type": "module" in package.json for Node.js.

Strict Mode

Strict Mode

Strict mode ('use strict') is an opt-in JavaScript mode that changes the language to be less forgiving — throwing errors for things that silently fail in normal mode. It was introduced in ES5 to make JavaScript safer and more predictable.

javascript
1// Enable strict mode for the whole file
2'use strict';
3
4// Or just for a function
5function strictFn() {
6 'use strict';
7 // ...
8}
9
10// What strict mode changes:
11
12// 1. Using undeclared variables throws ReferenceError
13try {
14 // undeclaredVar = 5; // ❌ ReferenceError in strict mode
15 // (silently creates a global in sloppy mode)
16 console.log('Undeclared var would throw in strict mode');
17} catch (e) { console.log(e.message); }
18
19// 2. Duplicate parameter names throw SyntaxError
20// function dup(a, a) {} // ❌ SyntaxError in strict mode
21
22// 3. 'this' in regular functions is undefined (not window)
23function checkThis() {
24 'use strict';
25 console.log('this in strict function:', this); // undefined
26}
27checkThis();
28
29// 4. Writing to read-only properties throws TypeError
30// const obj = Object.freeze({ x: 1 });
31// obj.x = 2; // ❌ TypeError in strict mode (silently ignored otherwise)
32
33console.log('Strict mode demonstrated!');
34
35// NOTE: ES Modules and class bodies are ALWAYS in strict mode
36// You don't need 'use strict' in .mjs files or inside class definitions

You're already in strict mode in modern code

ES Modules (import/export) and class bodies are automatically in strict mode — no 'use strict' needed. If you're writing modern JavaScript with a bundler like Vite, you're already protected. Only add 'use strict' explicitly in old CommonJS scripts.

Test Your Knowledge

Test Your Knowledge

Quick Check

Which of these is a valid JavaScript identifier?

Quick Check

What is the difference between == and === in JavaScript?

Quick Check

What will typeof null return?

Quick Check

Which variable declaration keyword should you use by default in modern JavaScript?

Quick Check

What is the difference between a statement and an expression?

Syntax Quick Reference

Syntax Quick Reference

Pro Tips
  • 1JavaScript is case-sensitiveconsole.logConsole.Log. Every character's case matters.
  • 2Use const by default. Switch to let only when you need to reassign. Never use var.
  • 3Always use strict equality === over loose equality == to avoid type coercion surprises.
  • 4Always wrap if, for, and while bodies in curly braces { } — even for single statements.
  • 5Use template literals (backticks) for strings that embed variables or span multiple lines.
  • 6Comments should explain why, not what. The code already shows what.
  • 7Semicolons are optional (ASI), but be consistent. Use Prettier to enforce your choice automatically.
  • 8ES Modules and class bodies are always in strict mode — no need to add 'use strict' manually.
What's Next?
📦

Variables & Data Types

Deep dive into let, const, and all 8 JavaScript data types.

Operators

Every operator in detail — arithmetic, comparison, logical, bitwise, and more.

🔀

Control Flow

if/else, switch, loops — mastering the flow of your programs.

🔧

Functions

Declarations, expressions, arrow functions, closures, and scope.

You know JavaScript syntax!

You can now write syntactically valid JavaScript. You understand statements, expressions, identifiers, literals, operators, comments, blocks, and modules. The next step is learning what to do with them — variables, data types, and control flow.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning