JavaScript Cheatsheet
A comprehensive reference guide with interactive examples
Variables and Data Types
JavaScript variables can be declared using var
, let
, or const
. JavaScript has dynamic types and several primitive data types.
// Variable declaration
let message = "Hello";
const pi = 3.14159;
var count = 10;
// Data types
let isActive = true; // boolean
let age = 25; // number
let name = "John"; // string
let value = null; // null
let notDefined; // undefined
let person = { firstName: "John", lastName: "Doe" }; // object
let numbers = [1, 2, 3]; // array
let uniqueId = Symbol("id"); // symbol
let bigNumber = 123456789012345678901234567890n; // bigint
Functions
Functions are blocks of code designed to perform a particular task. They can be declared in several ways.
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const square = function(x) {
return x * x;
};
// Arrow function (ES6+)
const multiply = (a, b) => a * b;
// IIFE (Immediately Invoked Function Expression)
(function() {
console.log("This runs immediately");
})();
Objects
Objects are collections of key-value pairs and are fundamental to JavaScript.
// Object creation
let person = {
name: "Alice",
age: 30,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
// Accessing properties
console.log(person.name); // Dot notation
console.log(person["age"]); // Bracket notation
// Object destructuring (ES6+)
const { name, age } = person;
// Adding properties
person.job = "Developer";
// Object methods
const keys = Object.keys(person);
const values = Object.values(person);
const entries = Object.entries(person);
Arrays
Arrays are used to store multiple values in a single variable.
// Array creation
let fruits = ["Apple", "Banana", "Orange"];
// Accessing elements
let first = fruits[0];
let last = fruits[fruits.length - 1];
// Array methods
fruits.push("Mango"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("Strawberry"); // Add to beginning
fruits.shift(); // Remove from beginning
// Iteration methods
fruits.forEach(function(item, index) {
console.log(index, item);
});
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
const sum = numbers.reduce((total, num) => total + num, 0);
// Spread operator (ES6+)
let newFruits = [...fruits, "Pineapple"];
DOM Manipulation
The Document Object Model (DOM) represents the page content as objects that can be manipulated with JavaScript.
// Selecting elements
const elementById = document.getElementById("myId");
const elementsByClass = document.getElementsByClassName("myClass");
const elementsByTag = document.getElementsByTagName("div");
const element = document.querySelector(".myClass"); // Returns first match
const elements = document.querySelectorAll("div.myClass"); // Returns all matches
// Modifying elements
element.textContent = "New text";
element.innerHTML = "Bold text";
element.setAttribute("class", "new-class");
element.style.color = "blue";
// Creating and appending elements
const newDiv = document.createElement("div");
newDiv.textContent = "I'm a new div!";
document.body.appendChild(newDiv);
// Event handling
element.addEventListener("click", function(event) {
console.log("Element clicked!", event);
});
// Event delegation
document.addEventListener("click", function(event) {
if (event.target.matches(".my-class")) {
// Handle click on .my-class elements
}
});
Async JavaScript
JavaScript provides several ways to handle asynchronous operations.
// Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data);
});
// Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
// reject("Error occurred");
}, 1000);
});
}
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/Await (ES2017)
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
getData();
// Fetch API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
ES6+ Features
ECMAScript 2015 (ES6) and later versions introduced many new features to JavaScript.
// Let and Const (block scoping)
if (true) {
let blockScoped = "I'm block scoped";
const constantValue = "I can't be reassigned";
}
// Template literals
const name = "John";
const greeting = `Hello, ${name}!`;
// Default parameters
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
// Destructuring
const [first, second] = arr1;
const { name, age } = person;
// Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
}
// Modules (export/import)
// In file1.js: export const pi = 3.14159;
// In file2.js: import { pi } from './file1.js';
// Arrow functions
const add = (a, b) => a + b;
// Promises (covered in Async section)
// Async/await (covered in Async section)