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.
1// Each line below is a statement2let name = 'Alice'; // declaration statement3name = 'Bob'; // assignment statement4console.log(name); // expression statement56if (name === 'Bob') { // if statement (block)7 console.log('Hello Bob!');8}910for (let i = 0; i < 3; i++) { // for statement (block)11 console.log(i);12}1314// Multiple statements can be on one line (not recommended)15let x = 1; let y = 2; console.log(x + y);1617// A block { } groups multiple statements together18{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.
1// ✅ With semicolons — explicit, clear, no surprises2const a = 5;3const b = 10;4console.log(a + b);56// ✅ Without semicolons — works fine (ASI inserts them)7const c = 58const d = 109console.log(c + d)1011// ❌ ASI FAILURE — classic bug12// 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 semicolon1617// ❌ Another ASI trap with return18function getValue() {19 return // ASI inserts ; here!20 { // this object is never returned21 value: 4222 }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.
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.
1// ✅ These are THREE different variables2let color = 'red';3let Color = 'green';4let COLOR = 'blue';5console.log(color, Color, COLOR); // red green blue67// ✅ Keywords must be lowercase8let x = 1; // ✅ correct9// Let x = 1; // ❌ SyntaxError — 'Let' is not a keyword10// LET x = 1; // ❌ SyntaxError1112// ✅ Built-in objects are case-sensitive too13console.log(typeof Math.PI); // 'number' ✅14// console.log(math.PI); // ❌ ReferenceError: math is not defined15// console.log(Math.pi); // ❌ undefined — 'pi' not 'PI'1617// ✅ Function names are case-sensitive18function greet() { return 'hello'; }19// greet() ✅ Greet() ❌ GREET() ❌20console.log(greet());2122// ✅ HTML attributes are NOT case-sensitive, but JS is23// onclick vs onClick vs ONCLICK — all work in HTML24// but in JavaScript: element.onclick (all lowercase)
Common Case Mistakes
console.Log()→ReferenceError(should beconsole.log)document.GetElementById()→TypeError(should begetElementById)Math.floor()→ ✅ correctmath.floor()→ReferenceError(should beMathwith capital M)Let,Const,Var→ allSyntaxError(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.
| Rule | Valid Examples | Invalid Examples |
|---|---|---|
| Must start with a letter, _ or $ | name, _count, $price | 1name, -value, @tag |
| Can contain letters, digits, _ or $ | user1, total_price, $el | user-name, my value, rate% |
| Cannot be a reserved keyword | let, myLet, letMe | let, const, for, if, class |
| Case-sensitive | userName, UserName (two names) | — |
| No spaces allowed | firstName, first_name | first name |
1// ✅ Valid identifiers2let name = 'Alice';3let userName = 'bob123';4let _private = 'hidden'; // underscore prefix = convention for private5let $element = null; // $ prefix = common in jQuery / DOM libs6let camelCase = true;7let CONSTANT = 3.14; // all-caps = convention for constants8let _123 = 'valid'; // digits allowed after first char910// ❌ Invalid identifiers (would cause SyntaxError)11// let 1name = 'bad'; // starts with a number12// let my-var = 'bad'; // hyphens not allowed13// let my var = 'bad'; // spaces not allowed14// let for = 'bad'; // reserved keyword15// let class = 'bad'; // reserved keyword1617console.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.
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 28);910// ✅ Use whitespace to make code readable11const result = (10 + 5) * 2 / 3;1213// ❌ Technically valid but unreadable14const result2=(10+5)*2/3;1516// Whitespace INSIDE strings IS significant17console.log('hello world'); // 'hello world' — space preserved18console.log('hello world'); // 'hello world' — two spaces preserved1920console.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.
Produces a VALUE.Can be used wherevera value is expected.Examples:5 + 3 → 8'hello' → 'hello'true → truex * 2 → (some number)Math.random() → (0–1)a > b → true/falsex = 5 → 5 (assignmentis also expr)[1, 2, 3] → array{ a: 1 } → object() => x + 1 → function
Performs an ACTION.Does NOT produce a valueyou 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 containexpressions inside them.
Produces a VALUE.Can be used wherevera value is expected.Examples:5 + 3 → 8'hello' → 'hello'true → truex * 2 → (some number)Math.random() → (0–1)a > b → true/falsex = 5 → 5 (assignmentis also expr)[1, 2, 3] → array{ a: 1 } → object() => x + 1 → function
Performs an ACTION.Does NOT produce a valueyou 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 containexpressions inside them.
1// Statements — perform actions2let x = 10; // declaration statement3if (x > 5) { console.log('big'); } // if statement4for (let i = 0; i < 2; i++) {} // for statement56// Expressions — produce values (usable inline)7const a = 5 + 3; // 5 + 3 is an expression → value 88const b = x > 5 ? 'big' : 'small'; // ternary expression → string9const c = Math.max(1, 2, 3); // function call expression → 310const d = [1, 2, 3].length; // property access expression → 31112console.log(a, b, c, d);1314// Expression statement — an expression used as a statement15console.log('hello'); // function call (expression) used as a statement16x++; // increment (expression) used as a statement1718// Can't use a statement where an expression is expected:19// const val = if (true) { 5 }; // ❌ SyntaxError — if is a statement20const val = true ? 5 : 0; // ✅ ternary is an expression21console.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.
1// Block with if2if (true) {3 console.log('Line 1 of block');4 console.log('Line 2 of block');5} // end of block67// Block with for8for (let i = 0; i < 3; i++) {9 const msg = `iteration ${i}`; // block-scoped variable10 console.log(msg);11}12// console.log(msg); // ❌ ReferenceError — 'msg' is scoped to the for block1314// Block with function15function add(a, b) {16 const result = a + b; // scoped to this block17 return result;18}19console.log(add(3, 4));2021// 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 scope2728// Single-line if WITHOUT block — valid but risky29if (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.
1// Number literals2console.log(42); // integer3console.log(3.14); // decimal (float)4console.log(-7); // negative5console.log(1_000_000); // numeric separator (ES2021) — same as 10000006console.log(0xFF); // hexadecimal — 2557console.log(0b1010); // binary — 108console.log(0o17); // octal — 159console.log(2e6); // scientific notation — 20000001011// String literals12console.log('single quotes');13console.log("double quotes");14console.log(`template literal — can span15multiple lines`);16console.log(`Hello ${'World'}!`); // template with expression1718// Boolean literals19console.log(true);20console.log(false);2122// Null & Undefined literals23console.log(null); // intentional absence of value24console.log(undefined); // variable declared but not assigned2526// Array literal27console.log([1, 'two', true, null]);2829// Object literal30console.log({ name: 'Alice', age: 25 });3132// RegExp literal33console.log(/^[a-z]+$/i); // regular expression3435// 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.
1// ── Arithmetic operators ─────────────────────────────────2console.log(10 + 3); // 13 — addition3console.log(10 - 3); // 7 — subtraction4console.log(10 * 3); // 30 — multiplication5console.log(10 / 3); // 3.3… — division6console.log(10 % 3); // 1 — modulus (remainder)7console.log(10 ** 3); // 1000 — exponentiation (ES2016)89let n = 5;10n++; console.log(n); // 6 — post-increment11++n; console.log(n); // 7 — pre-increment12n--; console.log(n); // 6 — post-decrement1314// ── Assignment operators ──────────────────────────────────15let x = 10; // assign16x += 5; console.log(x); // 15 — x = x + 517x -= 3; console.log(x); // 12 — x = x - 318x *= 2; console.log(x); // 24 — x = x * 219x /= 4; console.log(x); // 6 — x = x / 420x %= 4; console.log(x); // 2 — x = x % 421x **= 3; console.log(x); // 8 — x = x ** 32223// ── Comparison operators ──────────────────────────────────24console.log(5 == '5'); // true — loose (type coercion)25console.log(5 === '5'); // false — strict (no coercion) ← always use this26console.log(5 != '5'); // false — loose not-equal27console.log(5 !== '5'); // true — strict not-equal ← always use this28console.log(5 > 3); // true29console.log(5 < 3); // false30console.log(5 >= 5); // true31console.log(5 <= 4); // false3233// ── Logical operators ─────────────────────────────────────34console.log(true && false); // false — AND35console.log(true || false); // true — OR36console.log(!true); // false — NOT3738// ── String operator ───────────────────────────────────────39console.log('Hello' + ' ' + 'World'); // 'Hello World' — concatenation4041// ── Ternary operator ──────────────────────────────────────42const age = 20;43const status = age >= 18 ? 'adult' : 'minor';44console.log(status); // 'adult'4546// ── 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 bug52console.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.
| Syntax | Example | Special 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 ${}. |
1// Single and double quotes — identical behaviour2const a = 'Hello';3const b = "World";4console.log(a + ' ' + b); // Hello World56// Use the other quote to avoid escaping7const c = "It's a great day"; // ✅ no escape needed8const d = 'She said "hello"'; // ✅ no escape needed9const e = 'It\'s escaped'; // ✅ escaped apostrophe1011// Template literals — backticks12const name = 'Alice';13const age = 25;1415// Embed expressions with ${}16console.log(`Name: ${name}, Age: ${age}`);17console.log(`In 10 years: ${age + 10}`);18console.log(`Is adult: ${age >= 18 ? 'yes' : 'no'}`);1920// Multi-line strings — only works with backticks21const multiLine = `Line 122Line 223Line 3`;24console.log(multiLine);2526// Escape sequences — work in all three quote styles27console.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.
1// ── const — block-scoped, cannot be reassigned ───────────2const PI = 3.14159;3console.log(PI);4// PI = 3; // ❌ TypeError: Assignment to constant variable56// const with objects — the binding is constant, not the object7const user = { name: 'Alice' };8user.name = 'Bob'; // ✅ mutating the object is fine9// user = {}; // ❌ reassigning the binding is not10console.log(user.name); // 'Bob'1112// ── let — block-scoped, can be reassigned ─────────────────13let score = 0;14score = 10; // ✅ reassignment allowed15score += 5;16console.log(score); // 151718if (true) {19 let blockVar = 'inside block';20 console.log(blockVar); // ✅21}22// console.log(blockVar); // ❌ ReferenceError — block scoped2324// ── var — function-scoped, avoid in modern code ───────────25var oldStyle = 'legacy';26console.log(oldStyle);2728if (true) {29 var leaksOut = 'not block scoped!';30}31console.log(leaksOut); // ✅ 'not block scoped!' — var ignores blocks!3233// var hoisting — can use before declaration (bad)34console.log(hoisted); // undefined (not an error!)35var hoisted = 'value';36console.log(hoisted); // 'value'
| Keyword | Scope | Reassignable | Hoisted | Use When |
|---|---|---|---|---|
| const | Block | ❌ No | Yes (TDZ) | Default — use for everything |
| let | Block | ✅ Yes | Yes (TDZ) | When value needs to change |
| var | Function | ✅ Yes | Yes (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.
1// ── 1. Function Declaration ───────────────────────────────2// Hoisted — can be called before it's defined in the file3function add(a, b) {4 return a + b;5}6console.log(add(2, 3)); // 578// ── 2. Function Expression ────────────────────────────────9// Not hoisted — must be defined before calling10const multiply = function(a, b) {11 return a * b;12};13console.log(multiply(4, 3)); // 121415// ── 3. Arrow Function (ES6) ───────────────────────────────16// Concise syntax — no own 'this' binding17const subtract = (a, b) => a - b; // implicit return (one expression)18const square = x => x * x; // single param — no parens needed19const greet = () => 'Hello!'; // no params — empty parens needed20const divide = (a, b) => { // block body — explicit return needed21 if (b === 0) return 'Cannot divide by zero';22 return a / b;23};2425console.log(subtract(10, 3)); // 726console.log(square(5)); // 2527console.log(greet()); // 'Hello!'28console.log(divide(10, 2)); // 52930// ── 4. Method Shorthand (inside objects) ──────────────────31const calculator = {32 value: 0,33 add(n) { this.value += n; return this; }, // method shorthand34 subtract(n) { this.value -= n; return this; },35 result() { return this.value; },36};37console.log(calculator.add(10).subtract(3).result()); // 73839// ── 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.
1// ── if / else if / else ───────────────────────────────────2const score = 72;34if (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} // → C1314// ── Ternary (shorthand if/else for expressions) ───────────15const pass = score >= 50 ? 'Pass' : 'Fail';16console.log(pass); // 'Pass'1718// ── 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}3536// ── for loop ──────────────────────────────────────────────37for (let i = 0; i < 4; i++) {38 process.stdout ? process.stdout.write(i + ' ') : console.log(i);39}40console.log();4142// ── for...of — iterates values (arrays, strings) ──────────43const fruits = ['apple', 'banana', 'cherry'];44for (const fruit of fruits) {45 console.log(fruit);46}4748// ── 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}5354// ── while ─────────────────────────────────────────────────55let count = 3;56while (count > 0) {57 console.log(`Countdown: ${count}`);58 count--;59}6061// ── break and continue ────────────────────────────────────62for (let i = 0; i < 10; i++) {63 if (i === 3) continue; // skip 364 if (i === 6) break; // stop at 665 console.log(i); // 0, 1, 2, 4, 566}
Error Handling Syntax
Error Handling Syntax
JavaScript uses try...catch...finally to handle runtime errors gracefully instead of crashing the program.
1// ── try / catch ───────────────────────────────────────────2try {3 const result = JSON.parse('{ invalid json }'); // throws SyntaxError4 console.log(result); // never reached5} catch (error) {6 console.log('Caught:', error.message);7 console.log('Type:', error.constructor.name); // SyntaxError8}910// ── finally — runs regardless of error ────────────────────11function fetchData() {12 try {13 console.log('Fetching...');14 throw new Error('Network failure'); // simulate error15 console.log('Success'); // never runs16 } catch (err) {17 console.log('Error:', err.message);18 } finally {19 console.log('Cleanup — always runs (close DB, hide loader, etc.)');20 }21}22fetchData();2324// ── 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}3233try {34 console.log(divide(10, 2)); // 535 console.log(divide(10, 0)); // throws36} catch (e) {37 console.log('Caught:', e.message);38}3940// Built-in error types41// TypeError — wrong type42// RangeError — value out of range43// SyntaxError — invalid syntax44// 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.
1// ── math.js — EXPORTING ───────────────────────────────────23// Named exports — export multiple things4export const PI = 3.14159;56export function add(a, b) {7 return a + b;8}910export function subtract(a, b) {11 return a - b;12}1314// Default export — one per file15export default function multiply(a, b) {16 return a * b;17}181920// ── app.js — IMPORTING ────────────────────────────────────2122// Import named exports — use exact names in { }23import { PI, add, subtract } from './math.js';2425// Import default export — any name you choose26import multiply from './math.js';2728// Import both at once29import multiply, { PI, add } from './math.js';3031// Import everything as a namespace32import * as Math from './math.js';33Math.add(1, 2); // 334Math.PI; // 3.141593536// Rename on import37import { add as sum } from './math.js';38console.log(sum(3, 4)); // 73940// 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.
1// Enable strict mode for the whole file2'use strict';34// Or just for a function5function strictFn() {6 'use strict';7 // ...8}910// What strict mode changes:1112// 1. Using undeclared variables throws ReferenceError13try {14 // undeclaredVar = 5; // ❌ ReferenceError in strict mode15 // (silently creates a global in sloppy mode)16 console.log('Undeclared var would throw in strict mode');17} catch (e) { console.log(e.message); }1819// 2. Duplicate parameter names throw SyntaxError20// function dup(a, a) {} // ❌ SyntaxError in strict mode2122// 3. 'this' in regular functions is undefined (not window)23function checkThis() {24 'use strict';25 console.log('this in strict function:', this); // undefined26}27checkThis();2829// 4. Writing to read-only properties throws TypeError30// const obj = Object.freeze({ x: 1 });31// obj.x = 2; // ❌ TypeError in strict mode (silently ignored otherwise)3233console.log('Strict mode demonstrated!');3435// NOTE: ES Modules and class bodies are ALWAYS in strict mode36// 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
Which of these is a valid JavaScript identifier?
What is the difference between == and === in JavaScript?
What will typeof null return?
Which variable declaration keyword should you use by default in modern JavaScript?
What is the difference between a statement and an expression?
Syntax Quick Reference
Syntax Quick Reference
- 1JavaScript is case-sensitive —
console.log≠Console.Log. Every character's case matters. - 2Use
constby default. Switch toletonly when you need to reassign. Never usevar. - 3Always use strict equality
===over loose equality==to avoid type coercion surprises. - 4Always wrap
if,for, andwhilebodies 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.
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.
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).
// increment iis useless — the code already says that.// offset by 1 because array is 1-indexedis useful.// TODO:and// FIXME:comments to flag things to come back to. Most editors highlight these specially.