HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Array Methods

The basic structure of an HTML document consists of the following elements:

JavaScript provides a variety of built-in array methods that make it easy to work with arrays efficiently.


Here are some commonly used array methods:

  • push():
  • pop():
  • shift():
  • unshift():
  • concat():
  • slice():
  • splice():
  • forEach():

push():

Adds one or more elements to the end of an array and returns the new length of the array.

Example

let arr = [1, 2, 3];
arr.push(4);
// arr is now [1, 2, 3, 4]
 

pop():

Removes the last element from an array and returns that element.

Example

let arr = [1, 2, 3];
let removedElement = arr.pop();
// arr is now [1, 2], removedElement is 3
You can click on above box to edit the code and run again.

Output

shift(): :

Removes the first element from an array and returns that element.

Example

let arr = [1, 2, 3];
let shiftedElement = arr.shift();
// arr is now [2, 3], shiftedElement is 1
 

unshift():

Adds one or more elements to the beginning of an array and returns the new length of the array.

Example

let arr = [2, 3];
arr.unshift(1);
// arr is now [1, 2, 3]
 

concat()

Combines two or more arrays.

Example

let arr1 = [1, 2];
let arr2 = [3, 4];
let combinedArr = arr1.concat(arr2);
// combinedArr is [1, 2, 3, 4]
 

slice():

Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).

Example

let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(1, 3);
// newArr is [2, 3]

splice():

Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Example

let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, 'a', 'b');
// arr is now [1, 2, 'a', 'b', 4, 5]
 

forEach():

Executes a provided function once for each array element.

Example

let arr = [1, 2, 3];
arr.forEach(function(element) {
    console.log(element);
});
You can click on above box to edit the code and run again.

Output

Output: 1, 2, 3