JavaScript Cheatsheet

Key JavaScript syntax, methods, and ES6+ features

← Back to Cheatsheets

Variables and Data Types

Variable Declarations
// var (function scoped) var name = "John"; // let (block scoped) let age = 30; // const (block scoped, immutable reference) const PI = 3.14159; // Hoisting console.log(x); // undefined var x = 5; // Not hoisted // console.log(y); // ReferenceError let y = 10;
JavaScript variable declaration types
Data Types
// Primitive types let str = "Hello"; // String let num = 42; // Number let bool = true; // Boolean let n = null; // Null let u = undefined; // Undefined let sym = Symbol("id"); // Symbol let big = 123n; // BigInt // Reference types let obj = {}; // Object let arr = []; // Array let func = function(){}; // Function
JavaScript data types
Type Checking
typeof "hello" // "string" typeof 42 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" (quirk) typeof {} // "object" typeof [] // "object" typeof function(){} // "function" // Better array checking Array.isArray([]) // true Array.isArray({}) // false
Checking data types in JavaScript

Arrays

Array Creation and Basics
// Creating arrays let arr1 = [1, 2, 3]; let arr2 = new Array(1, 2, 3); let arr3 = Array.of(1, 2, 3); let arr4 = Array(5).fill(0); // [0,0,0,0,0] // Basic operations arr.length // Get length arr[0] // Access first element arr[arr.length-1] // Access last element arr.push(4) // Add to end arr.pop() // Remove from end arr.unshift(0) // Add to beginning arr.shift() // Remove from beginning
Array creation and basic operations
Array Methods
// Iteration arr.forEach(item => console.log(item)); arr.map(x => x * 2); arr.filter(x => x > 2); arr.find(x => x > 2); arr.findIndex(x => x > 2); arr.every(x => x > 0); arr.some(x => x > 2); // Transformation arr.reduce((acc, curr) => acc + curr, 0); arr.sort((a, b) => a - b); arr.reverse(); arr.slice(1, 3); // Extract portion arr.splice(1, 2); // Remove/add elements // Search arr.includes(2); arr.indexOf(2); arr.lastIndexOf(2);
Common array methods
ES6+ Array Methods
// Spread operator let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let combined = [...arr1, ...arr2]; // Destructuring let [first, second, ...rest] = [1, 2, 3, 4, 5]; // Array.from() let str = "hello"; let chars = Array.from(str); // ['h','e','l','l','o'] // find() and includes() let users = [{id: 1, name: "John"}]; let user = users.find(u => u.id === 1); let hasTwo = [1, 2, 3].includes(2);
Modern array features

Objects

Object Creation
// Object literal let obj1 = { name: "John", age: 30 }; // Constructor let obj2 = new Object(); obj2.name = "John"; // Constructor function function Person(name) { this.name = name; } let obj3 = new Person("John"); // ES6 Class class Person { constructor(name) { this.name = name; } } let obj4 = new Person("John"); // Object.create() let obj5 = Object.create(null);
Different ways to create objects
Object Methods
// Property access obj.name; // Dot notation obj["name"]; // Bracket notation // Property manipulation obj.age = 25; // Add/modify delete obj.age; // Delete "name" in obj; // Check property obj.hasOwnProperty("name"); // Check own property // Object methods Object.keys(obj); // Get keys Object.values(obj); // Get values Object.entries(obj); // Get [key, value] pairs Object.assign(target, obj); // Copy properties
Object property manipulation
ES6+ Object Features
// Shorthand properties let name = "John", age = 30; let obj = { name, age }; // { name: "John", age: 30 } // Computed property names let key = "dynamicKey"; let obj = { [key]: "value" }; // Method shorthand let obj = { sayHello() { return "Hello"; } }; // Destructuring let { name, age } = { name: "John", age: 30 }; let { name: userName } = { name: "John" }; // Rename // Spread operator let obj1 = { a: 1, b: 2 }; let obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
Modern object features

Functions

Function Declarations
// Function declaration function add(a, b) { return a + b; } // Function expression let add = function(a, b) { return a + b; }; // Arrow functions let add = (a, b) => a + b; let square = x => x * x; let greet = () => "Hello"; // Default parameters function multiply(a, b = 1) { return a * b; } // Rest parameters function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); }
Different function syntaxes
Advanced Functions
// IIFE (Immediately Invoked Function Expression) (function() { console.log("IIFE executed"); })(); // Callback functions function doSomething(callback) { callback(); } doSomething(() => console.log("Callback")); // Higher-order functions function multiplyBy(factor) { return (number) => number * factor; } let double = multiplyBy(2); // Closures function outer() { let privateVar = "secret"; return function() { return privateVar; }; } let inner = outer(); console.log(inner()); // "secret"
Advanced function concepts

ES6+ Features

Destructuring
// Array destructuring let [a, b] = [1, 2]; let [x, , y] = [1, 2, 3]; // Skip middle let [p, ...rest] = [1, 2, 3, 4]; // Rest // Object destructuring let { name, age } = { name: "John", age: 30 }; let { name: userName, age: userAge } = { name: "John", age: 30 }; // Default values let [x = 1, y = 2] = [3]; let { name = "Anonymous" } = {}; // Nested destructuring let { user: { name } } = { user: { name: "John" } };
ES6 destructuring syntax
Modules
// Exporting (math.js) export const PI = 3.14159; export function add(a, b) { return a + b; } export default function multiply(a, b) { return a * b; } // Importing import multiply, { PI, add } from './math.js'; import * as math from './math.js'; import { add as sum } from './math.js';
ES6 module system
Promises and Async/Await
// Promises let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Done!"), 1000); }); promise.then(result => console.log(result)) .catch(error => console.log(error)); // Async/Await async function fetchData() { try { let response = await fetch('/api/data'); let data = await response.json(); return data; } catch (error) { console.log(error); } }
Asynchronous JavaScript

DOM Manipulation

Selecting Elements
// Selecting elements document.getElementById("myId"); document.querySelector(".myClass"); document.querySelectorAll("p"); document.getElementsByClassName("myClass"); document.getElementsByTagName("div"); // Traversing element.parentElement; element.children; element.firstChild; element.nextSibling;
DOM element selection methods
Manipulating Elements
// Content element.textContent = "New text"; element.innerHTML = "<strong>HTML</strong>"; // Attributes element.setAttribute("class", "newClass"); element.getAttribute("class"); element.removeAttribute("class"); // Styles element.style.color = "red"; element.style.cssText = "color: red; font-size: 20px;"; // Classes element.classList.add("newClass"); element.classList.remove("oldClass"); element.classList.toggle("active"); element.classList.contains("className");
DOM element manipulation
Event Handling
// Adding event listeners element.addEventListener("click", function(e) { console.log("Clicked!"); }); // Removing event listeners element.removeEventListener("click", handler); // Event object element.addEventListener("click", function(e) { e.preventDefault(); // Prevent default action e.stopPropagation(); // Stop event bubbling console.log(e.target); // Element that triggered event }); // Common events // click, dblclick, mouseover, mouseout // keydown, keyup, keypress // load, resize, scroll // submit, change, focus, blur
DOM event handling