Top 10 essential JavaScript methods

RAMRAM
2 min read

1. Array.prototype.map(): Creates a new array by applying a function to each element of the original array.

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

2. Array.prototype.filter(): Creates a new array with elements that pass a test specified by a function.

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

3. Array.prototype.reduce(): Reduces the array to a single value by applying a function for each element.

const numbers = [1, 2, 3, 4, 5]; 
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); 
// sum: 15

4. Array.prototype.forEach(): Executes a provided function once for each array element.

const numbers = [1, 2, 3]; 
numbers.forEach(num => console.log(num)); 
// Output: 1, 2, 3 (each number printed on a new line)

5. Array.prototype.find(): Returns the first element in the array that satisfies the provided testing function.

const numbers = [1, 2, 3, 4, 5]; 
const evenNumber = numbers.find(num => num % 2 === 0); 
// evenNumber: 2

6. Array.prototype.includes(): Determines whether an array includes a certain value among its elements.

const numbers = [1, 2, 3]; 
const includesTwo = numbers.includes(2); 
// includesTwo: true

7. String.prototype.split(): Splits a string into an array of substrings based on a specified separator.

const sentence = "Hello, world!"; 
const words = sentence.split(" "); 
// words: ["Hello,", "world!"]

8. String.prototype.trim(): Removes whitespace from both ends of a string.

const paddedString = " Hello, world! "; 
const trimmedString = paddedString.trim(); 
// trimmedString: "Hello, world!"

9. String.prototype.includes(): Checks whether one string contains another string.

const sentence = "The quick brown fox jumps over"; 
const containsFox = sentence.includes("fox"); 
// containsFox: true

10. Object.keys(): Returns an array of a given object's own enumerable property names.

const person = { name: "John", age: 30, city: "NewYork" }; 
const keys = Object.keys(person); 
// keys: ["name", "age", "city"]
0
Subscribe to my newsletter

Read articles from RAM directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

RAM
RAM

Full Stack Developer since 2020.