Skip to content
DevNursery.com - New Web Developer Docs
GitHub

Javascript Cheatsheet

String Methods

String MethodPurposeExample
lengthReturns the length of a stringconst str = 'Hello';
const len = str.length;
charAt(index)Returns the character at the specified indexconst str = 'Hello';
const char = str.charAt(1);
charCodeAt(index)Returns the Unicode value of the character at the specified indexconst str = 'Hello';
const code = str.charCodeAt(0);
concat(...strings)Combines two or more strings and returns a new stringconst str1 = 'Hello';
const str2 = 'World';
const result = str1.concat(', ', str2);
indexOf(substring)Returns the index of the first occurrence of a substring in the stringconst str = 'Hello, World';
const index = str.indexOf('World');
lastIndexOf(substring)Returns the index of the last occurrence of a substring in the stringconst str = 'Hello, World, World';
const lastIndex = str.lastIndexOf('World');
includes(substring)Checks if a string contains a specified substringconst str = 'Hello, World';
const includesWorld = str.includes('World');
startsWith(substring)Checks if a string starts with a specified substringconst str = 'Hello, World';
const startsWithHello = str.startsWith('Hello');
endsWith(substring)Checks if a string ends with a specified substringconst str = 'Hello, World';
const endsWithWorld = str.endsWith('World');
toLowerCase()Converts a string to lowercaseconst str = 'Hello';
const lowerStr = str.toLowerCase();
toUpperCase()Converts a string to uppercaseconst str = 'Hello';
const upperStr = str.toUpperCase();
trim()Removes whitespace from the beginning and end of a stringconst str = ' Hello, World ';
const trimmedStr = str.trim();
trimStart() or trimLeft()Removes whitespace from the beginning of a stringconst str = ' Hello, World ';
const trimmedStr = str.trimStart();
trimEnd() or trimRight()Removes whitespace from the end of a stringconst str = ' Hello, World ';
const trimmedStr = str.trimEnd();
slice(start, end)Extracts a portion of a stringconst str = 'Hello, World';
const subStr = str.slice(7, 12);
substring(start, end)Extracts a portion of a string (similar to slice)const str = 'Hello, World';
const subStr = str.substring(7, 12);
substr(start, length)Extracts a specified number of characters from a stringconst str = 'Hello, World';
const subStr = str.substr(7, 5);
split(separator)Splits a string into an array of substringsconst str = 'apple,banana,orange';
const fruits = str.split(',');
replace(old, new)Replaces occurrences of a substring with another stringconst str = 'Hello, World';
const newStr = str.replace('World', 'Universe');
match(regexp)Searches for a specified pattern in the string and returns an array of matchesconst str = 'Hello, World';
const matches = str.match(/o/g);
search(regexp)Searches for a specified pattern in the string and returns the index of the first matchconst str = 'Hello, World';
const index = str.search(/o/);
matchAll(regexp)Returns an iterator of all matches of a specified pattern in the stringconst str = 'Hello, World';
const matches = [...str.matchAll(/o/g)];
startsWith()Checks if a string starts with a specified substring at a given indexconst str = 'Hello, World';
const startsWithHello = str.startsWith('Hello', 0);
endsWith()Checks if a string ends with a specified substring at a given indexconst str = 'Hello, World';
const endsWithWorld = str.endsWith('World', 11);
repeat(count)Returns a new string with a specified number of copies of the original stringconst str = 'Hello';
const repeatedStr = str.repeat(3);
padStart(length, padString)Pads the beginning of a string with a specified character(s) until it reaches a certain lengthconst str = '42';
const paddedStr = str.padStart(5, '0');
padEnd(length, padString)Pads the end of a string with a specified character(s) until it reaches a certain lengthconst str = '42';
const paddedStr = str.padEnd(5, '0');

Array Methods

Array MethodPurposeExample
lengthReturns the number of elements in an arrayconst numbers = [1, 2, 3];
const len = numbers.length;
push(element)Adds one or more elements to the end of an array and returns the new lengthconst fruits = ['apple', 'banana'];
fruits.push('orange', 'kiwi');
pop()Removes and returns the last element of an arrayconst fruits = ['apple', 'banana', 'orange'];
const lastFruit = fruits.pop();
unshift(element)Adds one or more elements to the beginning of an array and returns the new lengthconst numbers = [2, 3];
numbers.unshift(0, 1);
shift()Removes and returns the first element of an arrayconst fruits = ['apple', 'banana', 'orange'];
const firstFruit = fruits.shift();
concat(...arrays)Combines two or more arrays and returns a new arrayconst arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
join(separator)Joins all elements of an array into a string with the specified separatorconst fruits = ['apple', 'banana', 'orange'];
const fruitString = fruits.join(', ');
slice(start, end)Returns a shallow copy of a portion of an arrayconst numbers = [1, 2, 3, 4, 5];
const subArray = numbers.slice(1, 4);
splice(start, deleteCount, ...items)Adds or removes elements from an array at a specified positionconst numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 2, 6, 7);
indexOf(element)Returns the first index at which a specified element is found in an arrayconst fruits = ['apple', 'banana', 'orange'];
const index = fruits.indexOf('banana');
lastIndexOf(element)Returns the last index at which a specified element is found in an arrayconst fruits = ['apple', 'banana', 'orange', 'banana'];
const lastIndex = fruits.lastIndexOf('banana');
includes(element)Checks if an array includes a specified elementconst numbers = [1, 2, 3, 4, 5];
const includesThree = numbers.includes(3);
find(callback)Returns the first element in an array that satisfies the provided testing functionconst numbers = [1, 2, 3, 4, 5];
const found = numbers.find(num => num > 2);
findIndex(callback)Returns the index of the first element in an array that satisfies the provided testing functionconst numbers = [1, 2, 3, 4, 5];
const foundIndex = numbers.findIndex(num => num > 2);
filter(callback)Returns a new array with all elements that satisfy the provided testing functionconst numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
map(callback)Creates a new array with the results of calling a provided function on every element in the arrayconst numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
forEach(callback)Executes a provided function once for each array elementconst fruits = ['apple', 'banana', 'orange'];
fruits.forEach(fruit => console.log(fruit));
reduce(callback, initialValue)Reduces an array to a single value by applying a provided functionconst numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
reduceRight(callback, initialValue)Reduces an array from right to leftconst numbers = [1, 2, 3, 4, 5];
const product = numbers.reduceRight((accumulator, currentValue) => accumulator * currentValue, 1);
every(callback)Checks if all elements in an array satisfy a provided testing functionconst numbers = [1, 2, 3, 4, 5];
const allEven = numbers.every(num => num % 2 === 0);
some(callback)Checks if at least one element in an array satisfies a provided testing functionconst numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some(num => num % 2 === 0);
sort(compareFunction)Sorts the elements of an array in place based on the provided sorting criteriaconst fruits = ['banana', 'apple', 'orange'];
fruits.sort();
reverse()Reverses the order of elements in an arrayconst numbers = [1, 2, 3, 4, 5];
numbers.reverse();
fill(value, start, end)Changes all elements in an array to a specified value within a given rangeconst numbers = [1, 2, 3, 4, 5];
numbers.fill(0, 1, 4);
copyWithin(target, start, end)Copies a portion of an array to another location in the same arrayconst numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3, 5);
flat(depth)Creates a new array with all sub-array elements concatenated up to the specified depthconst nestedArray = [1, [2, 3], [4, [5]]];
const flatArray = nestedArray.flat(2);
flatMap(callback)Maps each element using a mapping function and flattens the result into a new arrayconst numbers = [1, 2, 3, 4, 5];
const doubledAndSquared = numbers.flatMap(num => [num * 2, num ** 2]);
from(iterable, mapFn, thisArg)Creates a new array from an iterable objectconst iterable = '12345';
const newArray = Array.from(iterable, Number);
of(...elements)Creates a new array with the specified elementsconst numbers = Array.of(1, 2, 3, 4, 5);

JavaScript Array Constructor

ActionExample Usage
Create an empty arraylet emptyArray = new Array();
Create an array with initial valueslet numbers = new Array(1, 2, 3);
Get the length of an arraylet length = myArray.length;
Access an element by indexlet element = myArray[index];
Add elements to the end of an arraymyArray.push(element1, element2);
Remove and return the last elementlet lastElement = myArray.pop();
Add elements to the beginning of an arraymyArray.unshift(element1, element2);
Remove and return the first elementlet firstElement = myArray.shift();
Find the index of an elementlet index = myArray.indexOf(element);
Check if an element exists in an arraylet exists = myArray.includes(element);
Remove an element by indexmyArray.splice(index, 1);
Copy an arraylet copyArray = new Array(...myArray);
Concatenate arrayslet combinedArray = array1.concat(array2);
Convert an array to a stringlet str = myArray.join(', ');

JavaScript Object Constructor

ActionExample Usage
Create an empty objectlet emptyObject = new Object();
Create an object with propertieslet person = new Object({ name: 'John', age: 30 });
Access a property by namelet value = myObject.propertyName;
Set a property by namemyObject.propertyName = value;
Check if an object has a propertylet hasProperty = myObject.hasOwnProperty('propertyName');
Delete a propertydelete myObject.propertyName;
Iterate over object propertiesfor (let key in myObject) { ... }
Copy an objectlet copyObject = Object.assign({}, myObject);
Merge objectslet mergedObject = Object.assign({}, obj1, obj2);
Convert an object to JSON stringlet jsonString = JSON.stringify(myObject);
Parse a JSON string to an objectlet parsedObject = JSON.parse(jsonString);

JavaScript JSON Object

ActionExample Usage
Parse a JSON string to an objectlet obj = JSON.parse(jsonString);
Convert an object to a JSON stringlet jsonString = JSON.stringify(obj);
Clone an objectlet clone = JSON.parse(JSON.stringify(obj));

JavaScript Math Object

ActionExample Usage
Generate a random number between 0 and 1let random = Math.random();
Generate a random integer between min and maxlet randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
Round a number to the nearest integerlet rounded = Math.round(number);
Calculate the square root of a numberlet sqrt = Math.sqrt(number);
Calculate the absolute value of a numberlet absValue = Math.abs(number);
Find the minimum of two or more numberslet minNumber = Math.min(num1, num2, ...);
Find the maximum of two or more numberslet maxNumber = Math.max(num1, num2, ...);
Calculate the sine, cosine, or tangentlet sine = Math.sin(angle);
Calculate the natural logarithmlet ln = Math.log(number);
Calculate the power of a numberlet power = Math.pow(base, exponent);
Round a number down to the nearest integerlet roundedDown = Math.floor(number);
Round a number up to the nearest integerlet roundedUp = Math.ceil(number);

JavaScript Function Object Methods

ActionExample Usage
Define a functionfunction myFunction(param1, param2) { ... }
Call a functionmyFunction(arg1, arg2);
Pass a function as an argumentfunction doSomething(callback) { ... }
Return a value from a functionreturn result;
Use the arguments objectlet arg1 = arguments[0];
Define anonymous functionslet add = function(x, y) { return x + y; };
Use arrow functionslet add = (x, y) => x + y;
Use function expressions in objects{ sayHello: function() { ... } }
Define and call immediately invoked function(function() { ... })();