Advertisement

Google Ad Slot: content-top

JS Array Methods


Method

Description

Example

length()

Returns the number of elements in the array

let arr = [5,2];
arr.length  // 2

push()

Adds an element to the end

let arr = [5,2];
arr.push(3) // [5,2,3]

unshift() 

Adds an element to the start 

let arr = [5,2,3];
arr.unshift(0) // [0,5,2,3]

shift()

Removes the first element

let arr = [5,2,3];
arr.shift() // [2,3]

pop()

Removes the last element

let arr = [5,2,3];
arr.pop() // [5,2]

indexOf()

Finds index of an element

let arr = [5,2,3];
arr.indexOf(2) // 1

includes()

Checks if an element exists

let arr = [5,2,3];
arr.includes(2) // true

length:

Returns the length of the array

Example
let arr = [5,2];
console.log(arr.length) // 2
Try it yourself

Add Element:

  • push() → Add to the end.
  • unshift() → Add to the beginning.
Example
let arr = ["1","2","3"];
arr.push("4");
console.log(arr); // ["1","2","3","4"]
arr.unshift("0");
console.log(arr); // ["0","1","2","3","4"]
Try it yourself

Remove Element:

  • pop() → Remove from the end.
  • shift() → Remove from the beginning.
Example
let arr = ["0","1","2","3","4"];
arr.pop();
console.log(arr); // ["0","1","2","3"]
arr.shift();
console.log(arr); // [1","2","3"]
Try it yourself

Search in Arrays:

  • indexof() → Find the index of a value.
  • includes() → Check if a value exists.
Example
let fruits = ["Apple","Banana","Cherry"];
console.log(fruits.indexOf("Banana")); // Output: 1
console.log(fruits.includes("Cherry")); // Output: true
Try it yourself