Advertisement
Google Ad Slot: content-top
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
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"]
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"]
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