🧠 AI Computer Institute
Content is AI-generated for educational purposes. Verify critical information independently. A bharath.ai initiative.

JavaScript Essentials Cheat Sheet

programmingGrades 9-127 sections

Variables & Data Types

// Variable declaration
var x = 10;        // Function-scoped (avoid)
let y = 20;        // Block-scoped (preferred)
const z = 30;      // Block-scoped, immutable

// Data types
let num = 42;
let str = "hello";
let bool = true;
let arr = [1, 2, 3];
let obj = {name: "Raj", age: 16};
let undef = undefined;
let nul = null;

// Type checking
typeof num;        // "number"
arr instanceof Array;  // true
Array.isArray(arr);    // true

// Template literals
let name = "Priya";
console.log(`Hello, ${name}!`);

Array Methods

let arr = [1, 2, 3, 4, 5];

// Transform
arr.map(x => x * 2);       // [2, 4, 6, 8, 10]
arr.filter(x => x > 2);    // [3, 4, 5]
arr.reduce((sum, x) => sum + x, 0);  // 15

// Search
arr.find(x => x > 3);      // 4
arr.findIndex(x => x > 3); // 3
arr.includes(3);           // true
arr.indexOf(3);            // 2

// Modify
arr.push(6);               // Add to end
arr.pop();                 // Remove from end
arr.unshift(0);            // Add to start
arr.shift();               // Remove from start
arr.slice(1, 3);           // [2, 3] (no mutation)
arr.splice(1, 2);          // Remove 2 at index 1 (mutates)

// Other
arr.reverse();             // Reverse in place
arr.sort((a, b) => a - b); // Sort numerically
arr.join(", ");            // "1, 2, 3, 4, 5"
arr.concat([6, 7]);        // [1, 2, 3, 4, 5, 6, 7]

Promises & Async/Await

// Promise
function fetchData(id) {
    return new Promise((resolve, reject) => {
        if (id > 0) {
            resolve({id: id, name: "Data"});
        } else {
            reject(new Error("Invalid ID"));
        }
    });
}

// Using then/catch
fetchData(1)
    .then(data => console.log(data))
    .catch(error => console.log(error))
    .finally(() => console.log("Done"));

// Async/Await (cleaner)
async function getData() {
    try {
        const data = await fetchData(1);
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}

// Promise.all (wait for all)
Promise.all([promise1, promise2, promise3])
    .then(results => console.log(results));

// Promise.race (first to complete)
Promise.race([promise1, promise2])
    .then(result => console.log(result));

DOM Manipulation

// Select elements
document.getElementById("myId");
document.querySelector(".myClass");
document.querySelectorAll("div");
document.getElementsByTagName("p");

// Manipulate content
element.textContent = "New text";      // Text only
element.innerHTML = "Bold";     // HTML
element.innerText = "Text";

// Attributes
element.getAttribute("data-value");
element.setAttribute("data-value", "123");
element.removeAttribute("data-value");
element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");

// Style
element.style.color = "red";
element.style.backgroundColor = "blue";

// Create & Append
const div = document.createElement("div");
div.textContent = "New div";
parent.appendChild(div);
parent.insertBefore(div, target);
parent.removeChild(div);

// Event listeners
element.addEventListener("click", function(e) {
    console.log("Clicked!");
    console.log(e.target);
});

element.addEventListener("submit", (e) => {
    e.preventDefault();  // Stop default behavior
});

ES6+ Features

// Arrow functions
const add = (a, b) => a + b;
const square = x => x * x;
const greet = () => "Hello";

// Destructuring
const {name, age} = {name: "Raj", age: 16};
const [a, b, ...rest] = [1, 2, 3, 4];

// Spread operator
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];  // [1, 2, 3, 4]
const obj1 = {a: 1};
const obj2 = {...obj1, b: 2};  // {a: 1, b: 2}

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

// for...of loop
for (const item of arr) {
    console.log(item);
}

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

const dog = new Animal("Buddy");
dog.speak();

// Modules
export const myFunction = () => {};
export default MyClass;
import MyClass, {myFunction} from "./module.js";

Common Patterns

// Higher-order function
function createMultiplier(multiplier) {
    return function(num) {
        return num * multiplier;
    };
}

const double = createMultiplier(2);
console.log(double(5));  // 10

// Closure
function counter() {
    let count = 0;
    return {
        increment: () => ++count,
        decrement: () => --count,
        get: () => count
    };
}

const c = counter();
console.log(c.increment());  // 1

// Callback
function fetchUser(id, callback) {
    setTimeout(() => {
        callback({id: id, name: "Raj"});
    }, 1000);
}

// Error handling
try {
    throw new Error("Something went wrong");
} catch (e) {
    console.log(e.message);
}

Regular Expressions (Regex)

// Create regex
const re1 = /pattern/g;        // Literal
const re2 = new RegExp("pattern", "g");

// Methods
"hello".match(/l+/);          // ["ll"]
"hello".replace(/l/, "L");    // "heLlo"
"hello".split(/l/);           // ["he", "", "o"]
/l/.test("hello");            // true
/l/.exec("hello");            // Match object

// Flags
/pattern/g   // Global (all matches)
/pattern/i   // Case-insensitive
/pattern/m   // Multiline
/pattern/gi  // Combine flags

// Common patterns
/d+/        // Digits
/w+/        // Word characters
/[a-z]/      // Lowercase
/[A-Z]/      // Uppercase
/[0-9a-zA-Z]/  // Alphanumeric
/^start/     // Start of string
/end$/       // End of string
/.+@.+..+/  // Email (simple)

More Cheat Sheets