JavaScript Syntax Cheat Sheet

Variable Declaration

let x = 10;       // Block-scoped, mutable  
const y = 20;     // Block-scoped, immutable  
var z = 30;       // Function-scoped  

Data Types

const str = "Hello";          // String  
const num = 42;               // Number  
const bool = true;            // Boolean  
const arr = [1, 2, 3];        // Array  
const obj = { key: "value" }; // Object  
const n = null;               // Null  
const u = undefined;          // Undefined  

Conditionals

if (x > 10) {
    console.log("x is greater than 10");
} else if (x === 10) {
    console.log("x is 10");
} else {
    console.log("x is less than 10");
}

Loops

for (let i = 0; i < 5; i++) {
  console.log(i);
}

let j = 0;
while (j < 5) {
    console.log(j);
    j++;
}

Arrow Functions

Implicit return for one-liner

const add = (a, b) => a + b;

Explicit return for multi-line

const multiply = (a, b) => {
  return a * b;
};

With Default Parameters

const greet = (name = "Guest") => `Hello, ${name}!`;

Array Methods

map()

const nums = [1, 2, 3];
const squares = nums.map(n => n * n); // [1, 4, 9]

filter()

const evens = nums.filter(n => n % 2 === 0); // [2]

reduce()

const sum = nums.reduce((acc, n) => acc + n, 0); // 6

forEach()

nums.forEach(n => console.log(n));

find() and findIndex()

const found = nums.find(n => n > 1);       // 2  
const index = nums.findIndex(n => n > 1); // 1  

Objects

Object Creation

const person = { name: "John", age: 30 };

Accessing Properties

console.log(person.name);      // Dot notation  
console.log(person["age"]);   // Bracket notation  

Object Destructuring

const { name, age } = person;
console.log(name, age);

Spread & Rest Operators

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // Spread: { a: 1, b: 2, c: 3 }

const { a, ...rest } = obj2;   // Rest: rest = { b: 2, c: 3 }

Sets & Maps

Set

const set = new Set([1, 2, 2, 3]);
console.log(set.has(2)); // true
set.add(4);
set.delete(1);
console.log([...set]);   // [2, 3, 4]

Map

const map = new Map();
map.set("key", "value");
console.log(map.get("key")); // "value"
map.delete("key");

Promises & Async/Await

Promises

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

Async/Await

const fetchData = async () => {
    try {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
};

fetchData();

Classes

Basic Class

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(`${this.name} makes a noise.`);
    }
}

const dog = new Animal("Dog");
dog.speak(); // Dog makes a noise.

Inheritance

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks.`);
    }
}

const dog = new Dog("Dog");
dog.speak(); // Dog barks.