JS Array Methods

Method

Description

Example

Returns the number of elements in the array

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

Adds an element to the end

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

Adds an element to the start 

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

Removes the first element

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

Removes the last element

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

Finds index of an element

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

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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.