learn.fttgsolutions.com · Cheat Sheets
Dynamic. Async. Everywhere.
| let | let name = 'Alice'; | Block-scoped variable. Can be reassigned. Preferred for values that change. |
| const | const PI = 3.14; | Block-scoped constant. Cannot be reassigned after declaration. Preferred by default. |
| var | var count = 0; | Function-scoped (or globally scoped). Hoisted to the top of its scope. Avoid in modern JS. |
| typeof | typeof 42 // 'number'
typeof 'hi' // 'string'
typeof true // 'boolean'
typeof null // 'object' (quirk)
typeof {} // 'object'
typeof [] // 'object'
typeof fn // 'function'
typeof undefined // 'undefined' | Returns a string describing the type of the operand. Note: typeof null === 'object' is a historical quirk. |
| null vs undefined | let a = null; // intentionally empty
let b; // undefined (not set) | null is an intentional absence of value. undefined means a variable was declared but never assigned. |
| Template literals | const msg = `Hello, ${name}!`; | Backtick strings allow embedded expressions (${}) and multi-line content. |
| Arithmetic | + - * / % ** | Add, subtract, multiply, divide, modulus (remainder), exponentiation (** is ES2016). |
| Strict equality | 1 === 1 // true
1 === '1' // false | === checks both value and type. Always prefer === over == to avoid implicit type coercion. |
| Loose equality | 0 == false // true
null == undefined // true | == performs type coercion before comparing. Can produce surprising results — use === instead. |
| Logical AND / OR | true && false // false
false || true // true | Short-circuit operators. && returns the first falsy value; || returns the first truthy value. |
| Nullish coalescing (??) | null ?? 'default' // 'default'
0 ?? 'default' // 0 | Returns the right side only if the left side is null or undefined. Unlike ||, 0 and '' are not treated as fallbacks. |
| Optional chaining (?.) | user?.address?.city | Safely access nested properties. Returns undefined instead of throwing if any intermediate value is null/undefined. |
| Ternary | const label = age >= 18 ? 'adult' : 'minor'; | Shorthand if/else expression. Returns one of two values based on a condition. |
| Spread (...) | const copy = [...arr];
const merged = { ...a, ...b }; | Expands an iterable or object into individual elements. Creates shallow copies. |
| Destructuring | const { name, age } = person;
const [first, second] = arr; | Unpack values from arrays or properties from objects into distinct variables. |
| length | 'hello'.length // 5 | Returns the number of characters in the string. |
| toUpperCase / toLowerCase | 'Hello'.toUpperCase() // 'HELLO' | Return a new string converted to upper or lower case. |
| trim() | ' hi '.trim() // 'hi' | Removes leading and trailing whitespace. |
| includes() | 'hello'.includes('ell') // true | Returns true if the string contains the given substring. |
| startsWith / endsWith | 'hello'.startsWith('he') // true | Check whether a string begins or ends with a given substring. |
| slice() | 'hello'.slice(1, 4) // 'ell' | Extracts a portion from start (inclusive) to end (exclusive). Negative indices count from the end. |
| replace() | 'foo bar'.replace('foo', 'baz') // 'baz bar' | Replaces the first match. Use /regex/g flag to replace all occurrences. |
| split() | 'a,b,c'.split(',') // ['a','b','c'] | Splits a string into an array using the given separator. |
| padStart / padEnd | '5'.padStart(3, '0') // '005' | Pads the start or end of a string to a target length. |
| repeat() | 'ab'.repeat(3) // 'ababab' | Returns the string repeated n times. |
| push / pop | arr.push('x'); // add to end
arr.pop(); // remove from end | push() adds one or more elements to the end and returns the new length. pop() removes and returns the last element. |
| unshift / shift | arr.unshift('x'); // add to start
arr.shift(); // remove from start | unshift() adds to the start; shift() removes and returns the first element. |
| map() | [1,2,3].map(n => n * 2) // [2,4,6] | Returns a new array with each element transformed by the callback. Does not mutate the original. |
| filter() | [1,2,3,4].filter(n => n > 2) // [3,4] | Returns a new array with only the elements for which the callback returns true. |
| reduce() | [1,2,3].reduce((acc, n) => acc + n, 0) // 6 | Reduces an array to a single value by applying the callback with an accumulator and current element. |
| find() / findIndex() | arr.find(n => n > 3) // first match
arr.findIndex(n => n > 3) // index of first match | find() returns the first matching element; findIndex() returns its index. Both return undefined/-1 if not found. |
| includes() | [1,2,3].includes(2) // true | Returns true if the array contains the given value. |
| some() / every() | arr.some(n => n > 3) // at least one match
arr.every(n => n > 0) // all match | some() returns true if any element passes; every() returns true only if all elements pass. |
| flat() / flatMap() | [[1,2],[3]].flat() // [1,2,3] | flat() flattens nested arrays by one level (or more with a depth argument). flatMap() combines map and flat. |
| slice() | [1,2,3,4].slice(1, 3) // [2,3] | Returns a shallow copy of a portion of the array. Does not mutate the original. |
| splice() | arr.splice(1, 2, 'x'); | Mutates the array: removes elements at index 1, removes 2 elements, and inserts 'x' in their place. |
| sort() | arr.sort((a, b) => a - b); // ascending numbers | Sorts in-place. Without a comparator, sorts as strings. Pass a comparator for numeric or custom sorts. |
| forEach() | arr.forEach(item => console.log(item)); | Executes a function for each element. Returns undefined — use map() if you need a new array. |
| Array.from() | Array.from('abc') // ['a','b','c']
Array.from({length:3}, (_,i) => i) // [0,1,2] | Creates a new array from an iterable or array-like object. Accepts an optional mapping function. |
| Object literal | const person = { name: 'Alice', age: 30 }; | Create an object with key/value pairs. Keys without spaces don't need quotes. |
| Shorthand property | const name = 'Alice';
const person = { name }; // same as { name: name } | If the variable name matches the key, you can omit the repetition. |
| Computed property | const key = 'color';
const obj = { [key]: 'blue' }; | Wrap the key in [] to use a dynamic expression as the property name. |
| Optional chaining | obj?.address?.city | Returns undefined instead of throwing when a property in the chain is null/undefined. |
| Object.keys() | Object.keys(obj) // ['name', 'age'] | Returns an array of an object's own enumerable property names. |
| Object.values() | Object.values(obj) // ['Alice', 30] | Returns an array of an object's own enumerable property values. |
| Object.entries() | Object.entries(obj) // [['name','Alice'],['age',30]] | Returns an array of [key, value] pairs for each own enumerable property. |
| Object.assign() | const merged = Object.assign({}, a, b); | Copies own enumerable properties from source objects into the target. Later sources overwrite earlier ones. |
| Spread merge | const merged = { ...a, ...b }; | Shallow merge objects. Properties in b overwrite matching properties in a. |
| delete operator | delete person.age; | Removes a property from an object. |
| Function declaration | function add(a, b) {
return a + b;
} | Hoisted to the top of its scope — can be called before it appears in the code. |
| Function expression | const add = function(a, b) {
return a + b;
}; | Not hoisted. Assigned to a variable like any other value. |
| Arrow function | const add = (a, b) => a + b; | Concise syntax. Implicit return when the body is a single expression (no braces). Does not bind its own this. |
| Default parameters | function greet(name = 'World') {
return `Hello, ${name}!`;
} | Provide a default value used when the argument is undefined or omitted. |
| Rest parameters | function sum(...nums) {
return nums.reduce((a, n) => a + n, 0);
} | Collects all remaining arguments into an array. |
| Callback | setTimeout(() => console.log('done'), 1000); | A function passed as an argument to another function, to be called later. |
| IIFE | (function() { console.log('runs immediately'); })(); | Immediately Invoked Function Expression — executes as soon as it is defined. |
| if / else if / else | if (x > 0) { ... }
else if (x === 0) { ... }
else { ... } | Standard conditional branching. |
| switch | switch (status) {
case 200: break;
case 404: break;
default: break;
} | Matches a value against cases. Include break to prevent fall-through. |
| for loop | for (let i = 0; i < 5; i++) { ... } | Classic counted iteration with init, condition, and update. |
| for...of | for (const item of arr) { ... } | Iterate over iterable values (arrays, strings, Maps, Sets). |
| for...in | for (const key in obj) { ... } | Iterate over an object's enumerable property keys. Avoid for arrays. |
| while / do-while | while (cond) { ... }
do { ... } while (cond); | while checks before each iteration. do-while always runs the body at least once. |
| break / continue | break; // exit loop
continue; // skip to next iteration | break exits the loop entirely. continue skips the remaining body for the current iteration. |
| Class definition | class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} speaks.`; }
} | A class is a blueprint for creating objects. The constructor initializes each instance. |
| Inheritance | class Dog extends Animal {
constructor(name) { super(name); }
speak() { return `${this.name} barks.`; }
} | extends inherits from a parent class. super() calls the parent constructor. |
| Static method | class MathHelper {
static add(a, b) { return a + b; }
}
MathHelper.add(1, 2); | Static methods belong to the class, not instances. Call directly on the class. |
| Getter / Setter | class Circle {
get area() { return Math.PI * this.r ** 2; }
set radius(v) { this.r = v; }
} | get/set allow property-like access while executing logic. |
| Private fields (ES2022) | class Counter {
#count = 0;
increment() { this.#count++; }
} | Fields prefixed with # are private — inaccessible outside the class. |
| Named export | export function add(a, b) { return a + b; }
export const PI = 3.14; | Export one or more named bindings from a module file. |
| Default export | export default function main() { ... } | Each module can have one default export. Import it with any name. |
| Named import | import { add, PI } from './math.js'; | Import specific named exports from a module. |
| Default import | import main from './main.js'; | Import the default export. The name is chosen by the importer. |
| Rename import | import { add as sum } from './math.js'; | Use as to rename an import to avoid naming conflicts. |
| Import all | import * as Math from './math.js'; | Import all named exports as properties of a namespace object. |
| Create | const p = new Promise((resolve, reject) => {
if (ok) resolve(value);
else reject(new Error('failed'));
}); | A Promise represents a value that may be available now, later, or never. Starts in pending state. |
| .then() | p.then(value => console.log(value)); | Registers a callback for when the promise resolves. Returns a new promise for chaining. |
| .catch() | p.catch(err => console.error(err)); | Registers a callback for when the promise rejects. |
| .finally() | p.finally(() => cleanup()); | Runs regardless of whether the promise resolved or rejected — good for cleanup. |
| Promise.all() | Promise.all([p1, p2, p3]).then(([r1, r2, r3]) => ...); | Waits for all promises to resolve. Rejects immediately if any one rejects. |
| Promise.allSettled() | Promise.allSettled([p1, p2]).then(results => ...); | Waits for all promises regardless of outcome. Each result has status (fulfilled/rejected) and value/reason. |
| Promise.race() | Promise.race([p1, p2]).then(first => ...); | Resolves or rejects as soon as the first promise settles. |
| async function | async function fetchData() {
const data = await getData();
return data;
} | Declares an async function. Always returns a Promise. Enables await inside the body. |
| await | const result = await somePromise; | Pauses execution of the async function until the promise settles. Unwraps the resolved value. |
| try / catch errors | async function load() {
try {
const data = await fetch(url);
} catch (err) {
console.error(err);
}
} | Use try/catch to handle rejected promises when using await. |
| Parallel with await | const [a, b] = await Promise.all([fetch(url1), fetch(url2)]); | Kick off multiple promises simultaneously, then await all of them together. |
| GET request | const res = await fetch('https://api.example.com/data');
const json = await res.json(); | fetch() returns a Promise. Call .json() on the response to parse the body as JSON. |
| POST request | const res = await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'item' }),
}); | Pass an options object to send POST with a JSON body. |
| Check status | if (!res.ok) throw new Error(`HTTP error: ${res.status}`); | fetch() does not reject on HTTP error codes (4xx, 5xx). Always check res.ok. |
| Response methods | res.json() // parse as JSON
res.text() // parse as plain text
res.blob() // parse as Blob (files, images) | Each response method returns a Promise. You can only consume the body once. |
| try / catch / finally | try {
riskyOperation();
} catch (err) {
console.error(err.message);
} finally {
cleanup();
} | try wraps risky code, catch receives the Error object, finally always runs. |
| throw | throw new Error('Something went wrong'); | Throw any value as an error. Prefer throwing Error objects so stack traces are available. |
| Error types | TypeError
RangeError
ReferenceError
SyntaxError | Built-in Error subtypes provide more specific information about what went wrong. |