·8 min read
JavaScript Cheat Sheet
Essential JavaScript syntax for everyday development. Covers modern ES6+ features you use daily.
Variables
const x = 10; // Cannot reassign let y = 20; // Can reassign var z = 30; // Old style, avoid
Data Types
const str = "hello";
const num = 42;
const bool = true;
const arr = [1, 2, 3];
const obj = { name: "Alice", age: 30 };
const nil = null;
const undef = undefined;Template Literals
const name = "Alice";
const msg = `Hello, ${name}! You are ${30 + 5} years old.`;Destructuring
// Array
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// Object
const { name, age, city = "NYC" } = person;Arrow Functions
const add = (a, b) => a + b;
const square = n => n * n;
const greet = name => {
return `Hello, ${name}`;
};Array Methods
const nums = [1, 2, 3, 4, 5]; nums.map(n => n * 2); // [2,4,6,8,10] nums.filter(n => n > 3); // [4,5] nums.reduce((sum, n) => sum + n, 0); // 15 nums.find(n => n > 3); // 4 nums.some(n => n > 4); // true nums.every(n => n > 0); // true nums.includes(3); // true nums.sort((a, b) => a - b); // sorted nums.flat(); // flatten nested
Objects
const person = { name: "Alice", age: 30 };
Object.keys(person); // ["name", "age"]
Object.values(person); // ["Alice", 30]
Object.entries(person); // [["name","Alice"],["age",30]]
const copy = { ...person, city: "NYC" };Promises and Async/Await
// Promise
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// Async/Await
async function getData() {
try {
const res = await fetch("/api/data");
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}Classes
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}Modules
// Export
export const PI = 3.14;
export default function calc() {}
// Import
import calc, { PI } from './math.js';Nullish Coalescing and Optional Chaining
const value = null ?? "default"; // "default" const city = user?.address?.city; // undefined if null