30 Essential JavaScript Methods You Should Know
JavaScript, the powerful language that powers the web, is packed with useful methods that can make your coding life easier. Here, we’ll explore 30 essential JavaScript methods, complete with examples and explanations to help you understand how to use them in your projects.
Table of Contents
Array Methods
1. Array.prototype.push()
Purpose: Adds one or more elements to the end of an array.
let fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // ['apple', 'banana', 'orange']
2. Array.prototype.pop()
Purpose: Removes the last element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop();
console.log(lastFruit); // 'orange'
console.log(fruits); // ['apple', 'banana']
3. Array.prototype.shift()
Purpose: Removes the first element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange'];
let firstFruit = fruits.shift();
console.log(firstFruit); // 'apple'
console.log(fruits); // ['banana', 'orange']
4. Array.prototype.unshift()
Purpose: Adds one or more elements to the beginning of an array.
let fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // ['apple', 'banana', 'orange']
5. Array.prototype.map()
Purpose: Creates a new array with the results of calling a function on every element in the original array.
Example with Arrays:
Let's say you have an array of numbers, and you want to create a new array where each number is doubled.
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
In this example, map() takes each number in the numbers array, multiplies it by 2, and returns a new array with the doubled values.
Example with Objects:
Now, let's see how map() can be used with an object. Suppose you have an object representing the prices of different products, and you want to apply a discount to each price.
let prices = {
apple: 1.0,
banana: 0.5,
cherry: 2.0
};
let discountedPrices = Object.fromEntries(
Object.entries(prices).map(([key, value]) => [key, value * 0.8])
);
console.log(discountedPrices);
// { apple: 0.8, banana: 0.4, cherry: 1.6 }
Here, Object.entries(prices) converts the object into an array of key-value pairs. map() then applies a 20% discount to each price, and Object.fromEntries() converts the result back into an object.
6. Array.prototype.filter()
Purpose: Creates a new array with all elements that pass the test implemented by the provided function.
Example with Arrays:
Suppose you have an array of numbers and want to filter out the odd numbers, keeping only the even numbers.
let numbers = [1, 2, 3, 4];
let even = numbers.filter(n => n % 2 === 0);
console.log(even); // [2, 4]
In this example, filter() checks each number in the array and only includes the numbers that are even in the new array.
Example with Objects:
Consider an object where the keys are product names and the values are the quantities available. You want to filter out products that are out of stock (quantity of 0).
let inventory = {
apple: 10,
banana: 0,
cherry: 5,
mango: 0
};
let inStock = Object.fromEntries(
Object.entries(inventory).filter(([key, value]) => value > 0)
);
console.log(inStock);
// { apple: 10, cherry: 5 }
In this case, Object.entries(inventory) converts the object into an array of key-value pairs, filter() removes the pairs where the quantity is 0, and Object.fromEntries() converts the filtered array back into an object.
7. Array.prototype.reduce()
Purpose: Executes a reducer function on each element of the array, resulting in a single output value.
Example with Arrays:
Let's say you want to sum all the numbers in an array.
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 10
In this example, reduce() iterates through each number in the array, adding it to the accumulator (acc), which starts at 0. The final result is the sum of all the numbers.
Example with Objects:
Now, consider you have an object representing the scores of players in a game, and you want to calculate the total score.
let scores = {
player1: 10,
player2: 15,
player3: 7
};
let totalScore = Object.entries(scores).reduce((acc, [key, value]) => acc + value, 0);
console.log(totalScore); // 32
Here, Object.entries(scores) converts the object into an array of key-value pairs, and reduce() sums up all the values (scores) to produce a total score.
8. Array.prototype.forEach()
Purpose: Executes a provided function once for each array element.
let numbers = [1, 2, 3];
numbers.forEach(n => console.log(n));
// 1
// 2
// 3
9. Array.prototype.find()
Purpose: Returns the first element that passes the test provided by the function.
let numbers = [1, 2, 3, 4];
let found = numbers.find(n => n > 2);
console.log(found); // 3
10. Array.prototype.findIndex()
Purpose: Returns the index of the first element that passes the test provided by the function.
let numbers = [1, 2, 3, 4];
let index = numbers.findIndex(n => n > 2);
console.log(index); // 2
11. Array.prototype.includes()
Purpose: Determines whether an array includes a certain value among its entries.
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false
12. Array.prototype.indexOf()
Purpose: Returns the first index at which a given element can be found in the array.
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // 1
13. Array.prototype.concat()
Purpose: Merges two or more arrays and returns a new array.
let array1 = [1, 2];
let array2 = [3, 4];
let combined = array1.concat(array2);
console.log(combined); // [1, 2, 3, 4]
14. Array.prototype.slice()
Purpose: Returns a shallow copy of a portion of an array into a new array.
let fruits = ['apple', 'banana', 'orange', 'grape'];
let citrus = fruits.slice(1, 3);
console.log(citrus); // ['banana', 'orange']
15. Array.prototype.splice()
Purpose: Adds/removes items to/from an array and returns the removed items.
let fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'grape');
console.log(fruits); // ['apple', 'grape', 'orange']
String Methods
16. String.prototype.split()
Purpose: Splits a string into an array of substrings.
let str = 'hello world';
let words = str.split(' ');
console.log(words); // ['hello', 'world']
17. String.prototype.trim()
Purpose: Removes whitespace from both ends of a string.
let str = ' hello world ';
let trimmed = str.trim();
console.log(trimmed); // 'hello world'
18. String.prototype.replace()
Purpose: Replaces a substring with a new substring in a string.
let str = 'hello world';
let newStr = str.replace('world', 'JavaScript');
console.log(newStr); // 'hello JavaScript'
19. String.prototype.toUpperCase()
Purpose: Converts a string to uppercase letters.
let str = 'hello';
let upperStr = str.toUpperCase();
console.log(upperStr); // 'HELLO'
20. String.prototype.toLowerCase()
Purpose: Converts a string to lowercase letters.
let str = 'HELLO';
let lowerStr = str.toLowerCase();
console.log(lowerStr); // 'hello'
Object Methods
21. Object.keys()
Purpose: Returns an array of a given object's property names.
let obj = {a: 1, b: 2, c: 3};
let keys = Object.keys(obj);
console.log(keys); // ['a', 'b', 'c']
22. Object.values()
Purpose: Returns an array of a given object's property values.
let obj = {a: 1, b: 2, c: 3};
let values = Object.values(obj);
console.log(values); // [1, 2, 3]
23. Object.entries()
Purpose: Returns an array of a given object's own enumerable string-keyed property [key, value]
pairs.
let obj = {a: 1, b: 2, c: 3};
let entries = Object.entries(obj);
console.log(entries); // [['a', 1], ['b', 2], ['c', 3]]
24. Object.assign()
Purpose: Copies the values of all enumerable own properties from one or more source objects to a target object.
let target = {a: 1};
let source = {b: 2, c: 3};
Object.assign(target, source);
console.log(target); // {a: 1, b: 2, c: 3}
25. Object.freeze()
Purpose: Freezes an object, preventing new properties from being added and existing properties from being removed or changed.
let obj = {a: 1};
Object.freeze(obj);
obj.a = 2; // This will have no effect
console.log(obj.a); // 1
26. Object.seal()
Purpose: Seals an object, preventing new properties from being added but allowing existing properties to be modified.
let obj = {a: 1};
Object.seal(obj);
obj.a = 2;
console.log(obj.a); // 2
Math Methods
27. Math.random()
Purpose: Returns a random floating-point number between 0 (inclusive) and 1 (exclusive).
let randomNum = Math.random();
console.log(randomNum); // A random number between 0 and 1
28. Math.floor()
Purpose: Returns the largest integer less than or equal to a given number.
let num = 5.9;
let floored = Math.floor(num);
console.log(floored); // 5
29. Math.ceil()
Purpose: Returns the smallest integer greater than or equal to a given number.
let num = 5.1;
let ceiled = Math.ceil(num);
console.log(ceiled); // 6
30. Math.max()
Purpose: Returns the largest of zero or more numbers.
let maxNum = Math.max(1, 3, 2);
console.log(maxNum); // 3
Conclusion
JavaScript offers a vast array of methods that can greatly simplify and enhance your development process. Understanding and effectively utilizing these methods—whether for arrays, strings, objects, or mathematical operations—allows you to write cleaner, more efficient, and more readable code.
Array methods like map(), filter(), and reduce() provide powerful ways to manipulate data collections, enabling transformations, filtering, and aggregation with minimal code. Similarly, string methods help you handle and format text effortlessly, while object methods give you the tools to manage and transform complex data structures. Math methods, though often overlooked, are essential for performing common numerical operations, from rounding to generating random values.
By mastering these 30 essential methods, you'll be better equipped to tackle everyday coding challenges, streamline your codebase, and write JavaScript that is both concise and powerful. As you continue to develop your skills, experimenting with these methods in different contexts will deepen your understanding and allow you to discover even more creative ways to solve problems with JavaScript.