JavaScript Syntax
JavaScript Syntax
Section titled “JavaScript Syntax”Understanding JavaScript syntax is fundamental to writing effective code. This guide covers all the essential building blocks of the language.
Variables and Declarations
Section titled “Variables and Declarations”Variable Declaration Keywords
Section titled “Variable Declaration Keywords”JavaScript has three ways to declare variables:
// let - block-scoped, mutablelet userName = 'Alice';userName = 'Bob'; // Can be reassigned
// const - block-scoped, immutable referenceconst 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 modifieduser.age = 30; // New properties can be added
// var - function-scoped, mutable (avoid in modern JavaScript)var oldStyle = 'legacy';
Variable Naming Rules
Section titled “Variable Naming Rules”// Valid variable namesconst 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 recommendedconst 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';
Variable Initialization
Section titled “Variable Initialization”// Declaration with initializationlet score = 0;const name = 'JavaScript';
// Declaration without initialization (undefined)let result;console.log(result); // undefined
// Multiple declarationslet a = 1, b = 2, c = 3;
// Destructuring assignmentconst [first, second] = [10, 20];const { name: userName, age } = { name: 'Alice', age: 25 };
Data Types
Section titled “Data Types”Primitive Types
Section titled “Primitive Types”// Numberconst integer = 42;const float = 3.14159;const negative = -17;const infinity = Infinity;const notANumber = NaN;
// Stringconst singleQuotes = 'Hello';const doubleQuotes = "World";const template = `Hello, ${name}!`;const multiline = ` This is a multiline string`;
// Booleanconst 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);
// Undefinedlet undefinedVar;console.log(undefinedVar); // undefined
// Nullconst emptyValue = null;
Reference Types
Section titled “Reference Types”// Objectconst person = { name: 'Alice', age: 30, address: { city: 'New York', country: 'USA' }};
// Arrayconst numbers = [1, 2, 3, 4, 5];const mixed = ['string', 42, true, null, { key: 'value' }];const sparse = [1, , , 4]; // Sparse array with holes
// Functionfunction greet(name) { return `Hello, ${name}!`;}
const arrow = (x, y) => x + y;const anonymous = function(x) { return x * 2; };
// Dateconst now = new Date();const specific = new Date('2024-01-01');
// RegExpconst pattern = /[a-z]+/gi;const regex = new RegExp('\\d+', 'g');
Operators
Section titled “Operators”Arithmetic Operators
Section titled “Arithmetic Operators”const a = 10, b = 3;
// Basic arithmeticconsole.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 decrementlet 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 operatorsconsole.log(+true); // 1 (convert to number)console.log(-'42'); // -42 (convert to number and negate)
Assignment Operators
Section titled “Assignment Operators”let x = 10;
// Compound assignmentx += 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 falsyconfig.theme &&= 'light'; // Assign if truthyconfig.theme ??= 'default'; // Assign if nullish
Comparison Operators
Section titled “Comparison Operators”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')
// Relationalconsole.log(a < c); // trueconsole.log(a > c); // falseconsole.log(a <= b); // trueconsole.log(a >= b); // true
// Special casesconsole.log(NaN === NaN); // falseconsole.log(Object.is(NaN, NaN)); // trueconsole.log(null == undefined); // trueconsole.log(null === undefined); // false
Logical Operators
Section titled “Logical Operators”const a = true, b = false, c = null;
// Boolean logicconsole.log(a && b); // false (AND)console.log(a || b); // true (OR)console.log(!a); // false (NOT)
// Short-circuit evaluationconst 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
Bitwise Operators
Section titled “Bitwise Operators”const a = 5; // 101 in binaryconst 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 and Statements
Section titled “Expressions and Statements”Expressions
Section titled “Expressions”Expressions produce values:
// Primary expressions42;'hello';true;null;this;[1, 2, 3];{ key: 'value' };
// Arithmetic expressions5 + 3;x * y;++counter;
// Function expressionsfunction(x) { return x * 2; };(x) => x * 2;
// Conditional (ternary) expressionconst result = age >= 18 ? 'adult' : 'minor';
// Complex expressionsconst total = items .filter(item => item.active) .map(item => item.price) .reduce((sum, price) => sum + price, 0);
Statements
Section titled “Statements”Statements perform actions:
// Declaration statementslet x = 5;const name = 'Alice';function greet() { return 'Hello'; }
// Expression statementsx++;console.log('Hello');greet();
// Block statements{ let localVar = 'scoped'; console.log(localVar);}
// Control flow statementsif (condition) { // do something}
for (let i = 0; i < 10; i++) { // loop body}
while (condition) { // loop body}
// Jump statementsreturn value;break;continue;throw new Error('Something went wrong');
String Literals and Templates
Section titled “String Literals and Templates”String Escaping
Section titled “String Escaping”// Escape sequencesconst 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
Template Literals
Section titled “Template Literals”const name = 'Alice';const age = 30;
// Basic interpolationconst greeting = `Hello, ${name}!`;
// Expressions in templatesconst message = `${name} will be ${age + 1} next year`;
// Multiline stringsconst html = ` <div class="user"> <h2>${name}</h2> <p>Age: ${age}</p> </div>`;
// Tagged template literalsfunction 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`;
Comments
Section titled “Comments”Single-line Comments
Section titled “Single-line Comments”// This is a single-line commentlet x = 5; // Comment at end of line
// TODO: Implement error handling// FIXME: This logic is flawed// NOTE: This function is deprecated
Multi-line Comments
Section titled “Multi-line Comments”/* * 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.`;}
Automatic Semicolon Insertion (ASI)
Section titled “Automatic Semicolon Insertion (ASI)”When Semicolons Are Required
Section titled “When Semicolons Are Required”// Generally safe without semicolonsconst name = 'Alice'const age = 30console.log(name, age)
// Dangerous cases - always use semicolonsconst 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 loopslet x = 5; let y = 10; // Multiple statements on one line
Best Practices
Section titled “Best Practices”// Recommended: Always use semicolons for clarityconst 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);
Common Syntax Patterns
Section titled “Common Syntax Patterns”Object Property Shorthand
Section titled “Object Property Shorthand”const name = 'Alice';const age = 30;
// Traditionalconst user1 = { name: name, age: age, greet: function() { return `Hello, ${this.name}`; }};
// Shorthand (ES6+)const user2 = { name, age, greet() { return `Hello, ${this.name}`; }};
Computed Property Names
Section titled “Computed Property Names”const propertyName = 'dynamicKey';const value = 'dynamicValue';
const obj = { [propertyName]: value, [`${propertyName}_modified`]: value.toUpperCase(), [Symbol.iterator]: function*() { yield* Object.values(this); }};
Destructuring Patterns
Section titled “Destructuring Patterns”// Array destructuringconst [first, second, ...rest] = [1, 2, 3, 4, 5];const [a, , c] = [1, 2, 3]; // Skip elements
// Object destructuringconst { name, age, email = 'not provided' } = user;const { name: userName, age: userAge } = user; // Rename
// Nested destructuringconst { address: { city, country } } = user;
// Function parameter destructuringfunction greetUser({ name, age = 'unknown' }) { return `Hello, ${name}! Age: ${age}`;}
Spread and Rest Syntax
Section titled “Spread and Rest Syntax”// Spread in arraysconst arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Spread in objectsconst defaults = { theme: 'dark', language: 'en' };const userPrefs = { language: 'es', fontSize: 14 };const config = { ...defaults, ...userPrefs }; // language: 'es' wins
// Rest in function parametersfunction sum(...numbers) { return numbers.reduce((total, num) => total + num, 0);}
// Rest in destructuringconst [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.