JavaScript is a versatile programming language that powers the web. With its dynamic nature and prototype-based object orientation, JavaScript provides developers with a robust toolset to build interactive web applications.
Mastering the essential JavaScript functions allows you to write cleaner, more efficient code. This guide will explore some of the most useful built-in functions that every JavaScript developer should know.
1. map()
The map() method is used to iterate over an array and transform each element using a callback function. It returns a new array with the transformed elements.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
Here, we double each number in the array using map(). The callback function is invoked for each element, taking the element as an argument and returning the transformed value.
map() is extremely useful for performing operations on each element of an array without mutating the original. Some common use cases include:
- Transforming data for display in UI
- Preparing data before saving to a database
- Performing calculations on arrays of numbers
One of the most common uses of map() is to transform data in React components:
const users = [
{ id: 1, name: ‘John‘ },
{ id: 2, name: ‘Sarah‘ },
];
function UserList() {
return (
<div>
{users.map(user => {
return <User key={user.id} name={user.name} />
})}
</div>
)
}
Here, we loop through the users array using map() to generate <User /> components.
2. filter()
The filter() method returns a new array containing only the elements that pass a test implemented by the callback function.
const ages = [22, 19, 24, 37, 40];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [22, 24, 37, 40]
In this example, filter() is used to return only adult ages (18+). The callback function tests each element against the condition and returns a boolean indicating if it passed.
filter() is extremely useful for filtering out unwanted elements from arrays. Some examples include:
- Filtering user lists based on criteria
- Removing invalid entries from arrays
- Finding elements that match a search query
3. reduce()
The reduce() method applies a reducer function to each element in an array to produce a single value. It takes two parameters:
- Accumulator – Stores the accumulated value as the array is traversed
- Current Value – The current element being processed
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => {
return accumulator + current;
}, 0);
console.log(sum); // 15
Here, reduce() is used to sum the array by adding each element into the accumulated value.
reduce() is commonly used to:
- Sum arrays of numbers
- Concatenate strings from an array
- Flattening nested arrays
- Performing aggregations in data analysis
It‘s an extremely powerful method that can condense complex operations into succinct code.
4. find()
The find() method returns the first element that satisfies the callback function. It short circuits after the first match is found.
const users = [
{ id: 1, name: ‘John‘},
{ id: 2, name: ‘Sarah‘},
{ id: 3, name: ‘Kyle‘},
];
const user = users.find(u => u.name === ‘Sarah‘);
console.log(user); // { id: 2, name: ‘Sarah‘ }
Here, find() is used to return the first user with name ‘Sarah‘. This avoids having to use a loop and break statement.
find() is useful for:
- Finding objects based on criteria
- Retrieving a user from a list by id
- Getting the first element matching a condition
It can greatly simplify logic compared to using loops and if statements.
5. some()
The some() method tests if at least one element in an array passes the test implemented by the callback function. It returns a boolean value.
const ages = [12, 17, 19, 24];
const hasAdults = ages.some(age => age >= 18);
console.log(hasAdults); // true
Here, some() is used to check if there is at least one adult age. It short circuits after finding the first match.
some() is useful for validating data and arrays:
- Checking if a value exists in an array
- Validating forms
- Checking if any elements match a criteria
It provides a cleaner alternative to iterating through arrays manually.
6. every()
The every() method checks if all elements in an array pass the test implemented by the callback function. It returns a boolean value.
const ages = [18, 22, 25, 28];
const allAdults = ages.every(age => age >= 18);
console.log(allAdults); // true
In this example, every() validates that all ages are 18+. It short circuits if any fail the test.
every() is useful for:
- Validating input data
- Checking arrays of objects against criteria
- Testing if all elements match a condition
It allows condensing multiple checks into a simple boolean check.
7. includes()
The includes() method checks if an array contains a specified element.
const languages = [‘JavaScript‘, ‘Python‘, ‘C++‘];
const hasJavaScript = languages.includes(‘JavaScript‘);
console.log(hasJavaScript); // true
This provides a simple way to check if a value exists in an array. Prior to includes(), developers would use indexOf() and check for -1 when the value was not found.
includes() is useful for:
- Checking if a form value exists in a list
- Validating user input against an allowlist
- Verifying the presence of data before processing
Overall, it simplifies membership checks on arrays.
8. indexOf()
The indexOf() method searches an array for a specified element and returns its first index. It returns -1 if the element is not found.
const colors = [‘red‘, ‘blue‘, ‘green‘, ‘blue‘];
const firstIndex = colors.indexOf(‘blue‘);
console.log(firstIndex); // 1
Here, indexOf() finds the first occurrence of ‘blue‘ in the array.
indexOf() has several important use cases:
- Checking if a value exists in an array
- Finding the index to insert/update elements
- Getting the position of elements for sorting
It provides fast lookup compared to manually iterating through arrays.
9. concat()
The concat() method merges two or more arrays, returning a new array.
const fruits = [‘apple‘, ‘banana‘];
const vegetables = [‘carrot‘, ‘potato‘];
const produce = fruits.concat(vegetables);
console.log(produce); // [‘apple‘, ‘banana‘, ‘carrot‘, ‘potato‘]
concat() provides an easy way to combine arrays without mutating the originals.
Some use cases include:
- Assembling arrays of data
- Combining results from multiple API calls
- Appending new elements to existing arrays
It‘s often used to merge state in React reducers immutably.
10. slice()
The slice() method copies a portion of an array into a new array. It takes two parameters:
begin– Zero-based starting indexend– Zero-based ending index (non-inclusive)
const arr = [1, 2, 3, 4, 5];
const subset = arr.slice(1, 3);
console.log(subset); // [2, 3]
Here, a slice from index 1 to 3 is returned. The original array is untouched.
slice() is commonly used to:
- Extract parts of arrays
- Split arrays into chunks
- Extracting subsets for pagination
It provides a simple way to get portions of arrays for further processing.
11. splice()
The splice() method changes the contents of an array by removing, replacing or adding elements.
It takes 3 parameters:
index– Location to start changing the arrayhowmany– Number of elements to removeitems– Elements to insert into the array
const fruits = [‘apple‘, ‘banana‘, ‘orange‘];
fruits.splice(1, 1, ‘grape‘);
console.log(fruits); // [‘apple‘, ‘grape‘, ‘orange‘]
Here, splice() removes 1 element starting at index 1 and inserts ‘grape‘.
splice() is commonly used to insert, remove or replace elements in an array. It directly mutates the original array.
12. Object.keys()
The Object.keys() method returns an array of the enumerable property names of an object.
const user = {
id: 101,
name: ‘Alice‘,
age: 25,
};
const keys = Object.keys(user);
console.log(keys); // [‘id‘, ‘name‘, ‘age‘]
This provides a simple way to get just the keys of an object as an array.
Object.keys() can be used to:
- Iterate over objects in a
for...ofloop - Get arrays of property names
- Convert objects into maps for efficient lookup
It enables converting objects into more array-like structures.
13. Object.values()
The Object.values() method returns an array of the enumerable property values of an object.
const user = {
id: 101,
name: ‘Alice‘,
age: 25,
};
const values = Object.values(user);
console.log(values); // [101, ‘Alice‘, 25]
This provides a clean way to get just the values of an object‘s properties.
Object.values() is useful for:
- Transforming objects into arrays
- Iterating through objects in a loop
- Serializing objects into lists of values
Combined with Object.keys(), you can easily transform objects into other data structures.
14. Object.entries()
The Object.entries() method returns an array of key-value pairs of the enumerable properties of an object.
const user = {
id: 101,
name: ‘Alice‘,
age: 25,
};
const entries = Object.entries(user);
console.log(entries); // [[‘id‘, 101], [‘name‘, ‘Alice‘], [‘age‘, 25]]
This provides a way to get both keys and values in a nested array.
Object.entries() can be used for:
- Converting objects into maps
- Serializing objects into kv pairs
- Getting keys and values for iteration
Combined with array methods like map(), filter() and reduce(), it unlocks powerful ways to transform objects.
Conclusion
JavaScript includes many built-in functions for transforming and processing data. Mastering their usage can greatly improve your code quality.
Functions like map(), filter() and reduce() embrace an immutable, declarative style that produces easy-to-understand code.
Methods like find(), includes() and indexOf() provide faster alternatives to manual iteration and checking values.
And object methods like Object.keys() make transforming objects into other data structures simple.
There are many more useful functions worth learning. The key is to thoroughly understand their use cases. This will allow you to recognize opportunities to use them in your code.
Instead of reaching for nested loops and conditionals, take advantage of what JavaScript already provides out of the box. Your code will be more terse, readable and less error-prone.