Skip to content

JavaScript Syntax

Understanding JavaScript syntax is fundamental to writing effective code. This guide covers all the essential building blocks of the language.

JavaScript has three ways to declare variables:

// let - block-scoped, mutable
let userName = 'Alice';
userName = 'Bob'; // Can be reassigned
// const - block-scoped, immutable reference
const API_URL = 'https://api.example.com';
// API_URL = 'new-url'; // TypeError: Assignment to constant variable
const user = { name: 'Alice' };
user.name = 'Bob'; // Object properties can still be modified
user.age = 30; // New properties can be added
// var - function-scoped, mutable (avoid in modern JavaScript)
var oldStyle = 'legacy';
// Valid variable names
const userName = 'Alice';
const _private = 'hidden';
const $element = document.getElementById('main');
const camelCase = 'preferred';
const PascalCase = 'for constructors';
const CONSTANT_VALUE = 'never changes';
// Valid but not recommended
const a = 1;
const x1 = 'data';
// Invalid variable names
// const 123invalid = 'starts with number';
// const user-name = 'contains hyphen';
// const class = 'reserved keyword';
// const my variable = 'contains space';
// Declaration with initialization
let score = 0;
const name = 'JavaScript';
// Declaration without initialization (undefined)
let result;
console.log(result); // undefined
// Multiple declarations
let a = 1, b = 2, c = 3;
// Destructuring assignment
const [first, second] = [10, 20];
const { name: userName, age } = { name: 'Alice', age: 25 };
// Number
const integer = 42;
const float = 3.14159;
const negative = -17;
const infinity = Infinity;
const notANumber = NaN;
// String
const singleQuotes = 'Hello';
const doubleQuotes = "World";
const template = `Hello, ${name}!`;
const multiline = `
This is a
multiline string
`;
// Boolean
const isActive = true;
const isComplete = false;
// Symbol (unique identifier)
const uniqueId = Symbol('id');
const globalSymbol = Symbol.for('app.id');
// BigInt (for large integers)
const bigNumber = 123456789012345678901234567890n;
const bigFromNumber = BigInt(123);
// Undefined
let undefinedVar;
console.log(undefinedVar); // undefined
// Null
const emptyValue = null;
// Object
const person = {
name: 'Alice',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};
// Array
const numbers = [1, 2, 3, 4, 5];
const mixed = ['string', 42, true, null, { key: 'value' }];
const sparse = [1, , , 4]; // Sparse array with holes
// Function
function greet(name) {
return `Hello, ${name}!`;
}
const arrow = (x, y) => x + y;
const anonymous = function(x) { return x * 2; };
// Date
const now = new Date();
const specific = new Date('2024-01-01');
// RegExp
const pattern = /[a-z]+/gi;
const regex = new RegExp('\\d+', 'g');
const a = 10, b = 3;
// Basic arithmetic
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (remainder/modulo)
console.log(a ** b); // 1000 (exponentiation)
// Increment and decrement
let counter = 5;
console.log(++counter); // 6 (pre-increment)
console.log(counter++); // 6 (post-increment, counter becomes 7)
console.log(--counter); // 6 (pre-decrement)
console.log(counter--); // 6 (post-decrement, counter becomes 5)
// Unary operators
console.log(+true); // 1 (convert to number)
console.log(-'42'); // -42 (convert to number and negate)
let x = 10;
// Compound assignment
x += 5; // x = x + 5; (15)
x -= 3; // x = x - 3; (12)
x *= 2; // x = x * 2; (24)
x /= 4; // x = x / 4; (6)
x %= 5; // x = x % 5; (1)
x **= 3; // x = x ** 3; (1)
// Logical assignment (ES2021)
let config = { theme: null };
config.theme ||= 'dark'; // Assign if falsy
config.theme &&= 'light'; // Assign if truthy
config.theme ??= 'default'; // Assign if nullish
const a = 5, b = '5', c = 10;
// Equality (type coercion)
console.log(a == b); // true (5 == '5')
console.log(a != c); // true (5 != 10)
// Strict equality (no type coercion)
console.log(a === b); // false (5 !== '5')
console.log(a !== b); // true (5 !== '5')
// Relational
console.log(a < c); // true
console.log(a > c); // false
console.log(a <= b); // true
console.log(a >= b); // true
// Special cases
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(null == undefined); // true
console.log(null === undefined); // false
const a = true, b = false, c = null;
// Boolean logic
console.log(a && b); // false (AND)
console.log(a || b); // true (OR)
console.log(!a); // false (NOT)
// Short-circuit evaluation
const user = { name: 'Alice' };
const name = user && user.name; // 'Alice'
const defaultName = user.name || 'Guest'; // 'Alice'
// Nullish coalescing (ES2020)
const setting = null;
const defaultSetting = setting ?? 'default'; // 'default'
console.log(0 ?? 'default'); // 0 (0 is not nullish)
console.log(null ?? 'default'); // 'default'
// Optional chaining (ES2020)
const person = { address: { street: '123 Main St' } };
console.log(person?.address?.street); // '123 Main St'
console.log(person?.phone?.number); // undefined
const a = 5; // 101 in binary
const b = 3; // 011 in binary
console.log(a & b); // 1 (001 - AND)
console.log(a | b); // 7 (111 - OR)
console.log(a ^ b); // 6 (110 - XOR)
console.log(~a); // -6 (NOT)
console.log(a << 1); // 10 (left shift)
console.log(a >> 1); // 2 (right shift)
console.log(a >>> 1); // 2 (unsigned right shift)

Expressions produce values:

// Primary expressions
42;
'hello';
true;
null;
this;
[1, 2, 3];
{ key: 'value' };
// Arithmetic expressions
5 + 3;
x * y;
++counter;
// Function expressions
function(x) { return x * 2; };
(x) => x * 2;
// Conditional (ternary) expression
const result = age >= 18 ? 'adult' : 'minor';
// Complex expressions
const total = items
.filter(item => item.active)
.map(item => item.price)
.reduce((sum, price) => sum + price, 0);

Statements perform actions:

// Declaration statements
let x = 5;
const name = 'Alice';
function greet() { return 'Hello'; }
// Expression statements
x++;
console.log('Hello');
greet();
// Block statements
{
let localVar = 'scoped';
console.log(localVar);
}
// Control flow statements
if (condition) {
// do something
}
for (let i = 0; i < 10; i++) {
// loop body
}
while (condition) {
// loop body
}
// Jump statements
return value;
break;
continue;
throw new Error('Something went wrong');
// Escape sequences
const escaped = 'Can\'t escape this: \"Hello\"';
const newline = 'Line 1\nLine 2';
const tab = 'Column1\tColumn2';
const backslash = 'Path: C:\\Users\\Alice';
const unicode = '\u0048\u0065\u006C\u006C\u006F'; // 'Hello'
// Raw strings (no escape processing)
const raw = String.raw`\n\t\r`; // Literal \n\t\r
const name = 'Alice';
const age = 30;
// Basic interpolation
const greeting = `Hello, ${name}!`;
// Expressions in templates
const message = `${name} will be ${age + 1} next year`;
// Multiline strings
const html = `
<div class="user">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// Tagged template literals
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i] ? `<mark>${values[i]}</mark>` : '';
return result + string + value;
}, '');
}
const highlighted = highlight`Hello ${name}, you are ${age} years old`;
// This is a single-line comment
let x = 5; // Comment at end of line
// TODO: Implement error handling
// FIXME: This logic is flawed
// NOTE: This function is deprecated
/*
* This is a multi-line comment
* that spans several lines
*/
/**
* JSDoc comment for documentation
* @param {string} name - The user's name
* @param {number} age - The user's age
* @returns {string} A greeting message
*/
function greet(name, age) {
return `Hello, ${name}! You are ${age} years old.`;
}
// Generally safe without semicolons
const name = 'Alice'
const age = 30
console.log(name, age)
// Dangerous cases - always use semicolons
const a = 1
;[1, 2, 3].forEach(console.log) // Safe with leading semicolon
const b = 2
;(function() { console.log('IIFE') })() // Safe with leading semicolon
// Always use semicolons in these cases:
for (let i = 0; i < 10; i++) { } // Required in for loops
let x = 5; let y = 10; // Multiple statements on one line
// Recommended: Always use semicolons for clarity
const user = {
name: 'Alice',
greet() {
return `Hello, ${this.name}!`;
}
};
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
const name = 'Alice';
const age = 30;
// Traditional
const user1 = {
name: name,
age: age,
greet: function() {
return `Hello, ${this.name}`;
}
};
// Shorthand (ES6+)
const user2 = {
name,
age,
greet() {
return `Hello, ${this.name}`;
}
};
const propertyName = 'dynamicKey';
const value = 'dynamicValue';
const obj = {
[propertyName]: value,
[`${propertyName}_modified`]: value.toUpperCase(),
[Symbol.iterator]: function*() {
yield* Object.values(this);
}
};
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
const [a, , c] = [1, 2, 3]; // Skip elements
// Object destructuring
const { name, age, email = 'not provided' } = user;
const { name: userName, age: userAge } = user; // Rename
// Nested destructuring
const { address: { city, country } } = user;
// Function parameter destructuring
function greetUser({ name, age = 'unknown' }) {
return `Hello, ${name}! Age: ${age}`;
}
// Spread in arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Spread in objects
const defaults = { theme: 'dark', language: 'en' };
const userPrefs = { language: 'es', fontSize: 14 };
const config = { ...defaults, ...userPrefs }; // language: 'es' wins
// Rest in function parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Rest in destructuring
const [head, ...tail] = [1, 2, 3, 4]; // head: 1, tail: [2, 3, 4]

This comprehensive syntax guide covers the fundamental building blocks of JavaScript. Understanding these concepts thoroughly will enable you to write clean, effective JavaScript code.


Practice these syntax patterns in the playground to reinforce your understanding.