JavaScript Cheat Sheet
JavaScript Cheat Sheet contains useful code examples on a single page. It is a quick reference guide for JavaScript developers to easily find code snippets and examples for common programming tasks and concepts.
String Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| charAt() | Returns the character at a specified index. | string.charAt(index) | "Hello".charAt(1) returns "e". |
| charCodeAt() | Returns the Unicode of the character at a specified index. | string.charCodeAt(index) | "ABC".charCodeAt(0) returns 65. |
| concat() | Joins two or more strings and returns a new string. | string1.concat(string2, ...) | "Hello".concat(" ", "World") returns "Hello World". |
| includes() | Checks if a string contains another string. | string.includes(substring) | "Hello".includes("ell") returns true. |
| endsWith() | Checks if a string ends with a specified substring. | string.endsWith(substring) | "Hello".endsWith("lo") returns true. |
| indexOf() | Returns the index of the first occurrence of a substring. | string.indexOf(substring) | "Hello".indexOf("l") returns 2. |
| lastIndexOf() | Returns the index of the last occurrence of a substring. | string.lastIndexOf(substring) | "Hello".lastIndexOf("l") returns 3. |
| match() | Searches for a match using a regular expression. | string.match(regex) | "Hello123".match(/\d+/) returns ["123"]. |
| repeat() | Returns a new string with a specified number of copies. | string.repeat(count) | "Hi".repeat(3) returns "HiHiHi". |
| replace() | Replaces matches with a new substring. | string.replace(search, replace) | "Hello".replace("l", "y") returns "Heylo". |
| replaceAll() | Replaces all matches with a new substring. | string.replaceAll(search, replace) | "Hello".replaceAll("l", "y") returns "Heyyo". |
| slice() | Extracts a section of a string and returns it as a new string. | string.slice(start, end) | "Hello".slice(1, 3) returns "el". |
| split() | Splits a string into an array of substrings. | string.split(separator) | "Hello, World".split(", ") returns ["Hello", "World"]. |
| startsWith() | Checks if a string starts with a specified substring. | string.startsWith(substring) | "Hello".startsWith("He") returns true. |
| substring() | Returns a substring between two indices. | string.substring(start, end) | "Hello".substring(1, 4) returns "ell". |
| toLowerCase() | Converts the string to lowercase letters. | string.toLowerCase() | "Hello".toLowerCase() returns "hello". |
| toUpperCase() | Converts the string to uppercase letters. | string.toUpperCase() | "Hello".toUpperCase() returns "HELLO". |
| trim() | Removes whitespace from both ends of a string. | string.trim() | " Hello ".trim() returns "Hello". |
| trimStart() | Removes whitespace from the beginning of a string. | string.trimStart() | " Hello".trimStart() returns "Hello". |
| trimEnd() | Removes whitespace from the end of a string. | string.trimEnd() | "Hello ".trimEnd() returns "Hello". |
| padStart() | Pads the current string with another string from the start. | string.padStart(targetLength, padString) | "5".padStart(3, "0") returns "005". |
| padEnd() | Pads the current string with another string from the end. | string.padEnd(targetLength, padString) | "5".padEnd(3, "0") returns "500". |
| localeCompare() | Compares two strings in the current locale. | string.localeCompare(otherString) | "a".localeCompare("b") returns -1. |
| toString() | Returns the value of the string object. | string.toString() | new String("Hello").toString() returns "Hello". |
| valueOf() | Returns the primitive value of a string object. | string.valueOf() | new String("Hello").valueOf() returns "Hello". |
Number Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| isNaN() | Checks whether a value is NaN. | Number.isNaN(value) | Number.isNaN("Hello") returns false. Number.isNaN(NaN) returns true. |
| isFinite() | Checks whether a value is a finite number. | Number.isFinite(value) | Number.isFinite(10) returns true. Number.isFinite(Infinity) returns false. |
| isInteger() | Checks whether a value is an integer. | Number.isInteger(value) | Number.isInteger(5) returns true. Number.isInteger(5.5) returns false. |
| isSafeInteger() | Checks whether a value is a safe integer. | Number.isSafeInteger(value) | Number.isSafeInteger(9007199254740991) returns true. Number.isSafeInteger(9007199254740992) returns false. |
| parseFloat() | Parses a string and returns a floating-point number. | Number.parseFloat(string) | Number.parseFloat("3.14") returns 3.14. |
| parseInt() | Parses a string and returns an integer of the specified radix. | Number.parseInt(string, radix) | Number.parseInt("10", 2) returns 2 (binary). |
| toExponential() | Converts a number to exponential notation. | num.toExponential(fractionDigits) | (123.456).toExponential(2) returns "1.23e+2". |
| toFixed() | Formats a number using fixed-point notation. | num.toFixed(digits) | (123.456).toFixed(2) returns "123.46". |
| toPrecision() | Formats a number to a specified length. | num.toPrecision(precision) | (123.456).toPrecision(4) returns "123.5". |
| toString() | Converts a number to a string. | num.toString(radix) | (255).toString(16) returns "ff" (hexadecimal). |
| valueOf() | Returns the primitive value of a number object. | num.valueOf() | new Number(123).valueOf() returns 123. |
| toLocaleString() | Converts a number to a string using local language format. | num.toLocaleString(locales, options) | (123456.789).toLocaleString("en-US") returns "123,456.789". |
| Number() | Converts a value to a number. | Number(value) | Number("123") returns 123. Number("abc") returns NaN. |
| Math.abs() | Returns the absolute value of a number. | Math.abs(value) | Math.abs(-5) returns 5. |
| Math.ceil() | Rounds a number up to the nearest integer. | Math.ceil(value) | Math.ceil(4.3) returns 5. |
| Math.floor() | Rounds a number down to the nearest integer. | Math.floor(value) | Math.floor(4.7) returns 4. |
| Math.round() | Rounds a number to the nearest integer. | Math.round(value) | Math.round(4.5) returns 5. Math.round(4.4) returns 4. |
| Math.max() | Returns the largest of zero or more numbers. | Math.max(...values) | Math.max(1, 3, 2) returns 3. |
| Math.min() | Returns the smallest of zero or more numbers. | Math.min(...values) | Math.min(1, 3, 2) returns 1. |
| Math.random() | Returns a random number between 0 and 1. | Math.random() | Math.random() might return 0.123456789. |
| Math.sqrt() | Returns the square root of a number. | Math.sqrt(value) | Math.sqrt(16) returns 4. |
| Math.pow() | Returns the base to the exponent power. | Math.pow(base, exponent) | Math.pow(2, 3) returns 8. |
Boolean Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| toString() | Converts a Boolean value to a string ("true" or "false"). | boolean.toString() | true.toString() returns "true". |
| valueOf() | Returns the primitive value of a Boolean object. | boolean.valueOf() | new Boolean(true).valueOf() returns true. |
| Boolean() | Converts a value to a Boolean (true or false). | Boolean(value) | Boolean(0) returns false. Boolean("Hello") returns true. |
Array Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| push() | Adds one or more elements to the end of an array and returns the new length of the array. | array.push(element1, element2, ...) | const arr = [1, 2]; arr.push(3); results in arr being [1, 2, 3]. |
| pop() | Removes the last element from an array and returns that element. | array.pop() | const arr = [1, 2, 3]; const last = arr.pop(); results in arr being [1, 2] and last being 3. |
| shift() | Removes the first element from an array and returns that element. | array.shift() | const arr = [1, 2, 3]; const first = arr.shift(); results in arr being [2, 3] and first being 1. |
| unshift() | Adds one or more elements to the beginning of an array and returns the new length of the array. | array.unshift(element1, element2, ...) | const arr = [2, 3]; arr.unshift(1); results in arr being [1, 2, 3]. |
| concat() | Merges two or more arrays into a new array without modifying the original arrays. | array1.concat(array2, ...) | const arr1 = [1, 2]; const arr2 = [3, 4]; const arr3 = arr1.concat(arr2); results in arr3 being [1, 2, 3, 4]. |
| join() | Joins all elements of an array into a string, with an optional separator. | array.join(separator) | const arr = [1, 2, 3]; const str = arr.join('-'); results in str being "1-2-3". |
| reverse() | Reverses the order of the elements in an array in place. | array.reverse() | const arr = [1, 2, 3]; arr.reverse(); results in arr being [3, 2, 1]. |
| slice() | Returns a shallow copy of a portion of an array into a new array. | array.slice(start, end) | const arr = [1, 2, 3, 4]; const sliced = arr.slice(1, 3); results in sliced being [2, 3]. |
| splice() | Adds or removes elements from an array. | array.splice(start, deleteCount, item1, item2, ...) | const arr = [1, 2, 3, 4]; arr.splice(1, 2, 'a', 'b'); results in arr being [1, 'a', 'b', 4]. |
| indexOf() | Returns the first index at which a given element can be found in the array, or -1 if it is not present. | array.indexOf(searchElement) | const arr = [1, 2, 3]; const index = arr.indexOf(2); results in index being 1. |
| lastIndexOf() | Returns the last index at which a given element can be found in the array, or -1 if it is not present. | array.lastIndexOf(searchElement) | const arr = [1, 2, 3, 2]; const index = arr.lastIndexOf(2); results in index being 3. |
| includes() | Determines whether an array includes a certain element, returning true or false. | array.includes(searchElement) | const arr = [1, 2, 3]; const hasTwo = arr.includes(2); results in hasTwo being true. |
| find() | Returns the first element in the array that satisfies the provided testing function. | array.find(callback) | const arr = [1, 2, 3]; const found = arr.find(num => num > 1); results in found being 2. |
| findIndex() | Returns the index of the first element in the array that satisfies the provided testing function. | array.findIndex(callback) | const arr = [1, 2, 3]; const index = arr.findIndex(num => num > 1); results in index being 1. |
| fill() | Fills all the elements of an array from a start index to an end index with a static value. | array.fill(value, start, end) | const arr = [1, 2, 3]; arr.fill(0, 1, 2); results in arr being [1, 0, 3]. |
| sort() | Sorts the elements of an array in place and returns the array. | array.sort(compareFunction) | const arr = [3, 1, 2]; arr.sort(); results in arr being [1, 2, 3]. |
Array Iteration Methods Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| forEach() | Executes a provided function once for each array element. | array.forEach(callback) | [1, 2, 3].forEach(num => console.log(num)); logs 1, 2, 3 to the console. |
| map() | Creates a new array with the results of calling a provided function on every element in the array. | array.map(callback) | const doubled = [1, 2, 3].map(num => num * 2); returns [2, 4, 6]. |
| filter() | Creates a new array with all elements that pass the test implemented by the provided function. | array.filter(callback) | const evens = [1, 2, 3, 4].filter(num => num % 2 === 0); returns [2, 4]. |
| reduce() | Executes a reducer function on each element of the array, resulting in a single output value. | array.reduce(callback, initialValue) | const sum = [1, 2, 3].reduce((acc, num) => acc + num, 0); returns 6. |
| reduceRight() | Applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. | array.reduceRight(callback, initialValue) | const joined = ['a', 'b', 'c'].reduceRight((acc, char) => acc + char, ''); returns 'cba'. |
| some() | Tests whether at least one element in the array passes the test implemented by the provided function. | array.some(callback) | const hasEven = [1, 2, 3].some(num => num % 2 === 0); returns true. |
| every() | Tests whether all elements in the array pass the test implemented by the provided function. | array.every(callback) | const allEven = [2, 4, 6].every(num => num % 2 === 0); returns true. |
| find() | Returns the first element in the array that satisfies the provided testing function. | array.find(callback) | const found = [1, 2, 3].find(num => num > 2); returns 3. |
| findIndex() | Returns the index of the first element in the array that satisfies the provided testing function. | array.findIndex(callback) | const index = [1, 2, 3].findIndex(num => num > 2); returns 2. |
| flatMap() | First maps each element using a mapping function, then flattens the result into a new array. | array.flatMap(callback) | const arr = [1, 2, 3].flatMap(num => [num, num * 2]); returns [1, 2, 2, 4, 3, 6]. |
| entries() | Returns a new Array Iterator object that contains the key/value pairs for each index in the array. | array.entries() | for (let [index, value] of ['a', 'b'].entries()) { console.log(index, value); } logs 0 'a' and 1 'b'. |
| keys() | Returns a new Array Iterator object that contains the keys for each index in the array. | array.keys() | for (let key of ['a', 'b'].keys()) { console.log(key); } logs 0 and 1. |
| values() | Returns a new Array Iterator object that contains the values for each index in the array. | array.values() | for (let value of ['a', 'b'].values()) { console.log(value); } logs 'a' and 'b'. |
Object Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| Object.assign() | Copies all enumerable own properties from one or more source objects to a target object. | Object.assign(target, ...sources) | const target = { a: 1 }; const source = { b: 2 }; Object.assign(target, source); results in target being { a: 1, b: 2 }. |
| Object.create() | Creates a new object with the specified prototype object and properties. | Object.create(proto, propertiesObject) | const obj = Object.create({ a: 1 }); creates an object with obj.__proto__ having { a: 1 }. |
| Object.keys() | Returns an array of a given object's own enumerable property names. | Object.keys(obj) | const obj = { a: 1, b: 2 }; const keys = Object.keys(obj); results in keys being ['a', 'b']. |
| Object.values() | Returns an array of a given object's own enumerable property values. | Object.values(obj) | const obj = { a: 1, b: 2 }; const values = Object.values(obj); results in values being [1, 2]. |
| Object.entries() | Returns an array of a given object's own enumerable property [key, value] pairs. | Object.entries(obj) | const obj = { a: 1, b: 2 }; const entries = Object.entries(obj); results in entries being [['a', 1], ['b', 2]]. |
| Object.freeze() | Freezes an object, preventing new properties from being added and existing properties from being removed or modified. | Object.freeze(obj) | const obj = { a: 1 }; Object.freeze(obj); obj.a = 2; keeps obj.a as 1. |
| Object.seal() | Seals an object, preventing new properties from being added while still allowing modification of existing properties. | Object.seal(obj) | const obj = { a: 1 }; Object.seal(obj); obj.a = 2; obj.b = 3; results in obj being { a: 2 }. |
| Object.getOwnPropertyDescriptor() | Returns a property descriptor for a named property on an object. | Object.getOwnPropertyDescriptor(obj, prop) | const obj = { a: 1 }; const desc = Object.getOwnPropertyDescriptor(obj, 'a'); results in desc being { value: 1, writable: true, enumerable: true, configurable: true }. |
| Object.getOwnPropertyDescriptors() | Returns an object containing all own property descriptors of an object. | Object.getOwnPropertyDescriptors(obj) | const obj = { a: 1 }; const descs = Object.getOwnPropertyDescriptors(obj); results in descs containing descriptors for each property. |
| Object.getOwnPropertyNames() | Returns an array of all own property names (including non-enumerable ones) of an object. | Object.getOwnPropertyNames(obj) | const obj = { a: 1, [Symbol('b')]: 2 }; const names = Object.getOwnPropertyNames(obj); results in names being ['a']. |
| Object.getPrototypeOf() | Returns the prototype (i.e., the value of the internal [[Prototype]] property) of the specified object. | Object.getPrototypeOf(obj) | const proto = Object.getPrototypeOf({}); returns the prototype of an empty object, typically Object.prototype. |
| Object.setPrototypeOf() | Sets the prototype (i.e., the internal [[Prototype]] property) of a specified object. | Object.setPrototypeOf(obj, prototype) | const obj = {}; Object.setPrototypeOf(obj, null); sets the prototype of obj to null. |
| Object.is() | Compares if two values are the same value (similar to === but more reliable for NaN and -0). | Object.is(value1, value2) | Object.is(NaN, NaN) returns true. Object.is(0, -0) returns false. |
| Object.isExtensible() | Determines if an object is extensible (i.e., whether new properties can be added to it). | Object.isExtensible(obj) | const obj = {}; const extensible = Object.isExtensible(obj); returns true unless the object is frozen or sealed. |
| Object.preventExtensions() | Prevents new properties from being added to an object (but existing properties can be modified or deleted). | Object.preventExtensions(obj) | const obj = {}; Object.preventExtensions(obj); obj.a = 1; does not add a to obj. |
| Object.defineProperty() | Adds or modifies a single property directly on an object, and returns the object. | Object.defineProperty(obj, prop, descriptor) | const obj = {}; Object.defineProperty(obj, 'a', { value: 1, writable: false }); adds a to obj with a value of 1 and makes it non-writable. |
| Object.defineProperties() | Adds or modifies multiple properties directly on an object, and returns the object. | Object.defineProperties(obj, props) | const obj = {}; Object.defineProperties(obj, { a: { value: 1, writable: false }, b: { value: 2 } }); adds a and b to obj. |
| Object.fromEntries() | Transforms a list of key-value pairs into an object. | Object.fromEntries(iterable) | const arr = [['a', 1], ['b', 2]]; const obj = Object.fromEntries(arr); results in obj being { a: 1, b: 2 }. |
Function Methods Methods
Method | Description | Syntax | Example |
|---|---|---|---|
| call() | Calls a function with a given this value and arguments provided individually. | func.call(thisArg, arg1, arg2, ...) | function greet() { return this.name; } const obj = { name: 'Alice' }; greet.call(obj); returns "Alice". |
| apply() | Calls a function with a given this value, and arguments provided as an array (or array-like object). | func.apply(thisArg, [argsArray]) | function sum(x, y) { return x + y; } sum.apply(null, [1, 2]); returns 3. |
| bind() | Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. | func.bind(thisArg, arg1, arg2, ...) | function greet(greeting) { return greeting + ', ' + this.name; } const obj = { name: 'Alice' }; const greetAlice = greet.bind(obj, 'Hello'); greetAlice(); returns "Hello, Alice". |
| toString() | Returns a string representing the source code of the function. | func.toString() | function sum(x, y) { return x + y; } sum.toString(); returns "function sum(x, y) { return x + y; }". |
| length (property) | Indicates the number of arguments expected by the function. | func.length | function sum(a, b, c) {} sum.length; returns 3. |
| name (property) | Returns the name of the function. | func.name | function myFunction() {} myFunction.name; returns "myFunction". |
| constructor (property) | Returns a reference to the function's constructor (usually Function). | func.constructor | function sum() {} sum.constructor === Function; returns true. |
| prototype (property) | Allows the assignment of properties and methods to a function’s prototype, enabling inheritance for objects created by that function. | func.prototype | function Person(name) { this.name = name; } Person.prototype.greet = function() { return 'Hello, ' + this.name; }; const alice = new Person('Alice'); alice.greet(); returns "Hello, Alice". |
| Function (constructor) | Creates a new Function object. | new Function(arg1, arg2, ..., body) | const sum = new Function('a', 'b', 'return a + b'); sum(1, 2); returns 3. |