5 Essential Array Methods Every JavaScript Developer Must Know



This content originally appeared on DEV Community and was authored by MANIKANDAN

What is a method?

A method is just a function inside an object,
and it represents what the object can do.

Now we are going to see some of the most frequently used built-in methods in JavaScript

Array methods()

1) push()

–> It is used to add one or more elements to the end of an array.
–> It also returns the new length of the array.

Syntax

array.push(element1, element2, ...);

Example

let tasks = ["Wake up", "Brush teeth"];

tasks.push("Exercise", "Read a book");

console.log(tasks);

Output

["Wake up", "Brush teeth", "Exercise", "Read a book"]

2) pop()

–>pop() removes the last element from the array
–> It returns the removed element

Syntax

array.pop();

Example

let tasks = ["Wake up", "Brush teeth", "Exercise", "Read a book"];

let removedTask = tasks.pop();

console.log(tasks);
console.log("Removed:", removedTask);

Output

["Wake up", "Brush teeth", "Exercise"]
Removed: Read a book

3) shift()

–>shift() removes the first element from the array
–> It returns the removed element

Syntax

array.shift();

Example

let tasks = ["Wake up", "Brush teeth", "Exercise", "Read a book"];

let removedTask = tasks.shift();

console.log(tasks);
console.log("Removed:", removedTask);

Output

["Brush teeth", "Exercise", "Read a book"]
Removed: Wake up

4) unshift()

–>unshift() adds one or more elements to the beginning of the array
–> It returns the new length of the array

Syntax

array.unshift();

Example

let tasks = ["Brush teeth", "Exercise", "Read a book"];

let newLength = tasks.unshift("Wake up");

console.log(tasks);
console.log("New Length:", newLength);

Output

["Wake up", "Brush teeth", "Exercise", "Read a book"]
New Length: 4

5) map()

–> map() creates a new array
–> It runs a function on every element of the original array
–> It does NOT change the original array

Syntax

array.map(function(element, index, array) {
// return new value
});

Example

let numbers = [1, 2, 3, 4];

let doubled = numbers.map(function(num) {
return num * 2;
});

console.log(numbers);
console.log(doubled);

Output

[1, 2, 3, 4]
[2, 4, 6, 8]


This content originally appeared on DEV Community and was authored by MANIKANDAN