ENGIMY.IO - CHEATSHEET
JS × QUICK REFERENCE
REFERENCE vES2024

JS Quick Reference

Everything you need day‑to‑day – syntax, examples, and modern features.

Variables

// let – block‑scoped, reassignable
let name = "Alice";
name = "Bob";

// const – block‑scoped, read‑only
const PI = 3.14159;
// PI = 3.14;  // Error

// var – function‑scoped (avoid)
var old = "legacy";

Data Types

Primitive Types
  • string"hello"
  • number42, 3.14, NaN, Infinity
  • bigint9007199254740991n
  • booleantrue / false
  • undefineddeclared but not assigned
  • nullintentional absence
  • symbolunique identifier
Objects (Reference)
  • Object{ key: value }
  • Array[1, 2, 3]
  • Functionfunction() {}
  • Datenew Date()
  • RegExp/pattern/
  • Map, Set, WeakMap, WeakSet

Type Checking

typeof 42          // "number"
typeof "hello"    // "string"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object" (bug)
typeof {}          // "object"
typeof []          // "object"
typeof function(){} // "function"

// Better checks
Array.isArray([])   // true
obj === null        // true check for null
Object.prototype.toString.call([]) // "[object Array]"

Functions

Declaration & Expression

// Function declaration
function add(a, b) {
    return a + b;
}

// Function expression
const subtract = function(a, b) {
    return a - b;
};

// Arrow function (ES6)
const multiply = (a, b) => a * b;

// Arrow with block body
const divide = (a, b) => {
    if (b === 0) throw new Error("Division by zero");
    return a / b;
};

Parameters & Arguments

// Default parameters
function greet(name = "Guest") {
    return `Hello, ${name}!`;
}

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((acc, n) => acc + n, 0);
}

// Spread operator (call)
const nums = [1, 2, 3];
const max = Math.max(...nums);

IIFE – Immediately Invoked Function Expression

(function() {
    console.log("IIFE");
})();

// Arrow IIFE
(() => {
    console.log("Arrow IIFE");
})();

Objects

Creation & Access

// Object literal
const person = {
    name: "Alice",
    age: 25,
    greet() {  // method shorthand
        console.log(`Hello, I'm ${this.name}`);
    }
};

// Access
person.name;        // "Alice"
person["age"];      // 25
person.greet();     // "Hello, I'm Alice"

// Computed property names
const key = "city";
const obj = { [key]: "Delhi" };

// Spread operator (shallow copy)
const copy = { ...person, city: "Delhi" };

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

Arrays

Basic Operations

const arr = [1, 2, 3, 4];

arr.push(5);          // add to end
arr.pop();            // remove last
arr.unshift(0);       // add to start
arr.shift();          // remove first
arr.indexOf(3);       // 2
arr.includes(3);      // true
arr.slice(1, 3);      // [2, 3] (copy)
arr.splice(1, 1);     // remove 1 at index 1

// Iteration
arr.forEach(x => console.log(x));
const doubled = arr.map(x => x * 2);
const evens = arr.filter(x => x % 2 === 0);
const sum = arr.reduce((acc, x) => acc + x, 0);

// Destructuring
const [first, second, ...rest] = arr;

Array Methods (Common)

arr.find(x => x > 2);        // first > 2
arr.findIndex(x => x > 2);  // index
arr.some(x => x > 10);      // any
arr.every(x => x > 0);      // all
arr.sort((a, b) => a - b);  // ascending
arr.reverse();              // reverse
arr.join(", ");            // "1, 2, 3"
arr.flat();                 // flatten one level
arr.flatMap(x => [x, x*2]); // map + flatten

Control Flow

if / else

if (x > 0) {
    console.log("positive");
} else if (x === 0) {
    console.log("zero");
} else {
    console.log("negative");
}

switch

switch (fruit) {
    case "apple":
        console.log("$1");
        break;
    case "banana":
        console.log("$0.5");
        break;
    default:
        console.log("Unknown");
}

Loops

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

// for...of (iterables)
for (const item of [1, 2, 3]) {
    console.log(item);
}

// for...in (object keys)
const obj = { a: 1, b: 2 };
for (const key in obj) {
    console.log(key, obj[key]);
}

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

// do...while
let i = 0;
do {
    console.log(i++);
} while (i < 5);

Classes (ES6)

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

class Dog extends Animal {
    constructor(name, breed) {
        super(name);
        this.breed = breed;
    }
    speak() {
        console.log(`${this.name} barks!`);
    }
    static description() {
        return "Dogs are loyal.";
    }
}

const dog = new Dog("Rex", "German Shepherd");
dog.speak();  // Rex barks!
console.log(Dog.description());  // Dogs are loyal.

Promises

// Creating a Promise
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        const success = true;
        if (success) resolve("Data");
        else reject("Error");
    }, 1000);
});

// Consuming
promise
    .then(data => console.log(data))
    .catch(err => console.error(err))
    .finally(() => console.log("Done"));

// Promise.all
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
Promise.all([p1, p2]).then(values => console.log(values)); // [1, 2]

// Promise.race
Promise.race([p1, p2]).then(value => console.log(value)); // 1

Async / Await

// Async function always returns a Promise
async function fetchData() {
    try {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Failed:", error);
        throw error;
    }
}

// Usage
fetchData()
    .then(data => console.log(data))
    .catch(err => console.error(err));

DOM Manipulation

// Selecting elements
const el = document.getElementById("myId");
const els = document.querySelectorAll(".class");
const first = document.querySelector("div");

// Creating elements
const newDiv = document.createElement("div");
newDiv.textContent = "Hello";
newDiv.classList.add("greeting");
document.body.appendChild(newDiv);

// Modifying attributes
el.setAttribute("data-value", "123");
const value = el.getAttribute("data-value");

// Styles
el.style.color = "red";
el.style.backgroundColor = "black";

// Inner HTML vs text
el.innerHTML = "<strong>bold</strong>";
el.textContent = "plain text";

Events

// Adding event listener
const btn = document.querySelector("#myButton");
btn.addEventListener("click", function(event) {
    console.log("Button clicked");
});

// Event object properties
btn.addEventListener("click", (e) => {
    e.preventDefault();   // prevent default action
    e.stopPropagation();  // stop bubbling
    console.log(e.target); // element that triggered
});

// Removing listener
const handler = () => console.log("clicked");
btn.addEventListener("click", handler);
btn.removeEventListener("click", handler);

// Common events
// click, mouseover, mouseout, keydown, keyup, submit, load, DOMContentLoaded

Error Handling

try {
    const result = riskyOperation();
} catch (error) {
    console.error("Caught:", error.message);
} finally {
    console.log("Cleanup");
}

// Throwing custom errors
function divide(a, b) {
    if (b === 0) throw new Error("Division by zero");
    return a / b;
}

Common Built‑ins

String Methods
  • str.length
  • str.toUpperCase()
  • str.toLowerCase()
  • str.trim()
  • str.split(separator)
  • str.join(separator) – (on array)
  • str.includes(sub)
  • str.startsWith(sub)
  • str.endsWith(sub)
  • str.replace(pattern, replacement)
  • str.slice(start, end)
  • str.substring(start, end)
Number / Math
  • Number.parseInt(str)
  • Number.parseFloat(str)
  • Math.abs(x)
  • Math.ceil(x)
  • Math.floor(x)
  • Math.round(x)
  • Math.max(...nums)
  • Math.min(...nums)
  • Math.random()
  • Math.pow(x, y)
  • Math.sqrt(x)

JSON

// Object to JSON string
const obj = { name: "Alice", age: 25 };
const jsonStr = JSON.stringify(obj);   // {"name":"Alice","age":25}

// JSON string to object
const parsed = JSON.parse(jsonStr);    // { name: "Alice", age: 25 }

// Pretty print
JSON.stringify(obj, null, 2);

Web Storage

// localStorage (persistent)
localStorage.setItem("key", "value");
const val = localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();

// sessionStorage (per tab)
sessionStorage.setItem("key", "value");

// Store objects (JSON)
localStorage.setItem("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(localStorage.getItem("user"));

Modules (ES6)

// Exporting
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { ... }

// Importing
import { PI, add } from "./math.js";
import Calculator from "./Calculator.js";

// Dynamic import
const module = await import("./module.js");

JavaScript Tips

  • Use const by default, let when reassignment is needed, avoid var.
  • Prefer arrow functions for callbacks and to preserve this.
  • Use === and !== instead of == and != to avoid type coercion bugs.
  • Handle promises with async/await or .catch().
  • Use spread ... for copying arrays/objects and function arguments.
  • Avoid global variables – use modules or IIFEs.
  • Use fetch() for network requests (modern alternative to XMLHttpRequest).
  • Use try/catch for async code inside async functions.
  • Use Object.freeze() for immutable objects (shallow).
  • Use Optional Chaining (?.) and Nullish Coalescing (??) for cleaner code.
📌 Quick Reference
Check your Node version: node -v
Run a script: node script.js
Browser console: Ctrl+Shift+I (or F12)
Use strict mode: "use strict"; at top of file
← Back to All Cheatsheets