📚 JavaScript Inbuilt Methods

Comprehensive reference with definitions and examples for all built-in JavaScript methods

Array

map

Creates a new array by applying a function to each element

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
// Result: [2, 4, 6, 8]

filter

Creates a new array with elements that pass a test

const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
// Result: [2, 4]

reduce

Reduces array to single value by applying function

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Result: 10

forEach

Executes a function for each array element

const fruits = ['apple', 'banana'];
fruits.forEach(fruit => console.log(fruit));

find

Returns first element that satisfies condition

const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const user = users.find(u => u.id === 2);
// Result: {id: 2, name: 'Bob'}

findIndex

Returns index of first element that satisfies condition

const numbers = [5, 12, 8, 130, 44];
const index = numbers.findIndex(n => n > 10);
// Result: 1

some

Tests if at least one element passes condition

const numbers = [1, 2, 3, 4];
const hasEven = numbers.some(n => n % 2 === 0);
// Result: true

every

Tests if all elements pass condition

const numbers = [2, 4, 6];
const allEven = numbers.every(n => n % 2 === 0);
// Result: true

includes

Checks if array contains a value

const fruits = ['apple', 'banana', 'mango'];
const hasBanana = fruits.includes('banana');
// Result: true

flat

Flattens nested arrays by specified depth

const nested = [1, [2, [3, 4]]];
const flattened = nested.flat(2);
// Result: [1, 2, 3, 4]

flatMap

Maps then flattens the result by one level

const arr = [1, 2, 3];
const result = arr.flatMap(x => [x, x * 2]);
// Result: [1, 2, 2, 4, 3, 6]

slice

Returns shallow copy of array portion

const fruits = ['apple', 'banana', 'mango', 'orange'];
const citrus = fruits.slice(2, 4);
// Result: ['mango', 'orange']

splice

Changes array by removing/replacing/adding elements

const fruits = ['apple', 'banana', 'mango'];
fruits.splice(1, 1, 'orange');
// Result: ['apple', 'orange', 'mango']

push / pop

push: adds to end, pop: removes from end

const stack = [1, 2];
stack.push(3); // [1, 2, 3]
stack.pop();   // [1, 2]

shift / unshift

shift: removes from start, unshift: adds to start

const arr = [2, 3];
arr.unshift(1); // [1, 2, 3]
arr.shift();    // [2, 3]

concat

Merges two or more arrays

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
// Result: [1, 2, 3, 4]

join

Joins array elements into a string

const words = ['Hello', 'World'];
const sentence = words.join(' ');
// Result: 'Hello World'

reverse

Reverses array in place

const arr = [1, 2, 3];
arr.reverse();
// Result: [3, 2, 1]

sort

Sorts array in place

const numbers = [3, 1, 4, 1, 5];
numbers.sort((a, b) => a - b);
// Result: [1, 1, 3, 4, 5]

fill

Fills array elements with static value

const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
// Result: [1, 0, 0, 4]

indexOf

Returns first index of value, or -1

const arr = ['a', 'b', 'c', 'b'];
const index = arr.indexOf('b');
// Result: 1

lastIndexOf

Returns last index of value, or -1

const arr = ['a', 'b', 'c', 'b'];
const index = arr.lastIndexOf('b');
// Result: 3

at

Returns element at index (supports negative)

const arr = [1, 2, 3, 4];
const last = arr.at(-1);
// Result: 4

Array.from

Creates array from array-like or iterable

const str = 'hello';
const chars = Array.from(str);
// Result: ['h', 'e', 'l', 'l', 'o']

Array.isArray

Checks if value is an array

Array.isArray([1, 2, 3]); // true
Array.isArray('hello');   // false

Array.of

Creates array from arguments

const arr = Array.of(1, 2, 3);
// Result: [1, 2, 3]

String

slice

Extracts part of string

const str = 'Hello World';
const part = str.slice(0, 5);
// Result: 'Hello'

substring

Extracts characters between two indices

const str = 'Hello World';
const part = str.substring(6, 11);
// Result: 'World'

split

Splits string into array

const str = 'a,b,c';
const arr = str.split(',');
// Result: ['a', 'b', 'c']

trim / trimStart / trimEnd

Removes whitespace from string

const str = '  hello  ';
str.trim();      // 'hello'
str.trimStart(); // 'hello  '
str.trimEnd();   // '  hello'

replace / replaceAll

Replaces substring(s)

const str = 'hello world';
str.replace('world', 'there'); // 'hello there'
'aaa'.replaceAll('a', 'b');    // 'bbb'

includes

Checks if string contains substring

const str = 'Hello World';
str.includes('World'); // true

startsWith / endsWith

Checks if string starts/ends with substring

const str = 'Hello World';
str.startsWith('Hello'); // true
str.endsWith('World');   // true

indexOf / lastIndexOf

Returns index of substring or -1

const str = 'hello world';
str.indexOf('o');     // 4
str.lastIndexOf('o'); // 7

toUpperCase / toLowerCase

Converts string case

const str = 'Hello';
str.toUpperCase(); // 'HELLO'
str.toLowerCase(); // 'hello'

padStart / padEnd

Pads string to target length

const str = '5';
str.padStart(3, '0'); // '005'
str.padEnd(3, '0');   // '500'

repeat

Repeats string n times

const str = 'ha';
str.repeat(3); // 'hahaha'

charAt / charCodeAt

Gets character or character code at index

const str = 'Hello';
str.charAt(0);     // 'H'
str.charCodeAt(0); // 72

match / matchAll

Matches string against regex

const str = 'test1 test2';
str.match(/\d/g); // ['1', '2']

search

Searches for regex match, returns index

const str = 'hello world';
str.search(/world/); // 6

at

Returns character at index (supports negative)

const str = 'hello';
str.at(-1); // 'o'

template literals

String interpolation with backticks

const name = 'Alice';
const greeting = `Hello, ${name}!`;
// Result: 'Hello, Alice!'

Object

Object.keys

Returns array of object's keys

const obj = {a: 1, b: 2};
Object.keys(obj);
// Result: ['a', 'b']

Object.values

Returns array of object's values

const obj = {a: 1, b: 2};
Object.values(obj);
// Result: [1, 2]

Object.entries

Returns array of [key, value] pairs

const obj = {a: 1, b: 2};
Object.entries(obj);
// Result: [['a', 1], ['b', 2]]

Object.assign

Copies properties from source to target

const target = {a: 1};
const source = {b: 2};
Object.assign(target, source);
// Result: {a: 1, b: 2}

Object.freeze

Freezes object (immutable)

const obj = {a: 1};
Object.freeze(obj);
obj.a = 2; // Fails silently
// obj is still {a: 1}

Object.seal

Seals object (can't add/remove properties)

const obj = {a: 1};
Object.seal(obj);
obj.a = 2;  // Works
obj.b = 3;  // Fails

Object.create

Creates object with specified prototype

const proto = {greet() { return 'Hi'; }};
const obj = Object.create(proto);
obj.greet(); // 'Hi'

Object.hasOwn

Checks if object has own property

const obj = {a: 1};
Object.hasOwn(obj, 'a'); // true
Object.hasOwn(obj, 'toString'); // false

Object.fromEntries

Creates object from [key, value] pairs

const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
// Result: {a: 1, b: 2}

Object.is

Compares two values for equality

Object.is(NaN, NaN);  // true
Object.is(0, -0);     // false
Object.is({}, {});    // false

Number

toFixed

Formats number to fixed decimal places

const num = 3.14159;
num.toFixed(2); // '3.14'

toString

Converts number to string

const num = 255;
num.toString();   // '255'
num.toString(16); // 'ff' (hex)

parseInt / parseFloat

Parses string to number

parseInt('42');      // 42
parseFloat('3.14'); // 3.14
parseInt('FF', 16); // 255

Number.isNaN

Checks if value is NaN

Number.isNaN(NaN);    // true
Number.isNaN('hello'); // false

Number.isFinite

Checks if value is finite number

Number.isFinite(42);       // true
Number.isFinite(Infinity); // false

Number.isInteger

Checks if value is integer

Number.isInteger(42);   // true
Number.isInteger(3.14); // false

Math

Math.max / Math.min

Returns maximum/minimum value

Math.max(1, 5, 3);  // 5
Math.min(1, 5, 3);  // 1
Math.max(...[1,2,3]); // 3

Math.floor / ceil / round

Rounds number down/up/nearest

Math.floor(3.7); // 3
Math.ceil(3.2);  // 4
Math.round(3.5); // 4

Math.abs

Returns absolute value

Math.abs(-5);  // 5
Math.abs(3);   // 3

Math.sqrt / Math.pow

Square root and power

Math.sqrt(16);     // 4
Math.pow(2, 3);    // 8
2 ** 3;            // 8 (same)

Math.random

Returns random number [0, 1)

Math.random(); // 0.547...
Math.floor(Math.random() * 10); // 0-9

Math.trunc

Removes decimal part

Math.trunc(3.7);  // 3
Math.trunc(-3.7); // -3

Promise

Promise.all

Waits for all promises to resolve

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
Promise.all([p1, p2]).then(console.log);
// [1, 2]

Promise.allSettled

Waits for all promises to settle

const p1 = Promise.resolve(1);
const p2 = Promise.reject('error');
Promise.allSettled([p1, p2]);
// [{status:'fulfilled',value:1}, {status:'rejected',reason:'error'}]

Promise.race

Returns first settled promise

const slow = new Promise(r => setTimeout(() => r('slow'), 100));
const fast = Promise.resolve('fast');
Promise.race([slow, fast]); // 'fast'

Promise.any

Returns first fulfilled promise

const p1 = Promise.reject('err');
const p2 = Promise.resolve('ok');
Promise.any([p1, p2]); // 'ok'

.then / .catch / .finally

Handles promise results

fetch('/api/data')
  .then(res => res.json())
  .catch(err => console.error(err))
  .finally(() => console.log('Done'));

JSON

JSON.stringify

Converts JavaScript value to JSON string

const obj = {name: 'Alice', age: 30};
JSON.stringify(obj);
// '{"name":"Alice","age":30}'

JSON.parse

Parses JSON string to JavaScript value

const json = '{"name":"Alice"}';
const obj = JSON.parse(json);
// {name: 'Alice'}

Date

new Date()

Creates date object

const now = new Date();
const specific = new Date('2024-01-01');

Date.now

Returns current timestamp (ms)

const timestamp = Date.now();
// 1704067200000

getFullYear / getMonth / getDate

Gets date components

const date = new Date('2024-03-15');
date.getFullYear(); // 2024
date.getMonth();    // 2 (0-indexed)
date.getDate();     // 15

toISOString

Converts date to ISO string

const date = new Date('2024-01-01');
date.toISOString();
// '2024-01-01T00:00:00.000Z'

Map & Set

Map

Key-value pairs with any key type

const map = new Map();
map.set('key', 'value');
map.get('key');  // 'value'
map.has('key');  // true
map.delete('key');
map.size;        // 0

Set

Collection of unique values

const set = new Set([1, 2, 2, 3]);
set.size;      // 3
set.has(2);    // true
set.add(4);
set.delete(1);
[...set];      // [2, 3, 4]

Console

console.log / warn / error

Logs messages to console

console.log('Info');
console.warn('Warning');
console.error('Error');

console.table

Displays data as table

const users = [{name:'Alice',age:30}, {name:'Bob',age:25}];
console.table(users);

console.time / timeEnd

Measures execution time

console.time('loop');
for(let i = 0; i < 1000; i++) {}
console.timeEnd('loop');