Array Methods for Javascript Beginners

Array Methods for Javascript Beginners

let's Talk about what is an array

In JavaScript, an Array is a data structure to store multiple elements in an ordered way.

Syntax

// square brackets (usual)
let arr = [item1, item2...];

// new Array (Recent Update)
let arr = new Array(item1, item2...);

Array methods


Array Length

Finding the total count of the elements in the array

let fruits = ["Apple", "Orange", "Guava"];

alert( fruits.length );

 // 3

Adding elements to Array

Pop() removes the last element of an array and returns it

let fruits = ["Apple", "Orange", "Guava"];

alert( fruits.pop() ); 
// remove "Guava" and alert it

alert( fruits ); 
// *Output* : Apple, Orange

Shift() removes the first element of an array and returns it

let fruits = ["Apple", "Orange", "Guava"];

alert( fruits.shift() ); 
// remove Apple and alert it

alert( fruits ); 
// *Output* : Orange, Guava

Adding elements to Array

Push() adds a new element to the end of an array

let fruits = ["Apple", "Orange",];

fruits.push("Guava"); 
// Guava is added at the end

alert( fruits ); 
// *Output* : Apple, Orange, Guava

Unshift() adds a new element to the beginning of an array

let fruits = ["Orange", "Guava"];

fruits.unshift('Apple');
// Apple is added at the start

alert( fruits ); 
// *Output* : Apple, Orange, Guava

Splice and Slice

Splice remove/replace elements or adding new elements

let arr = ["Apple", "Orange", "Guava"];

arr.splice(1, 1, "Grapes"); 
// from index 1 remove 1 element and add Grapes

alert( arr ); 
// *Output* : Apple, Grapes, Guava

//now arr = ["Apple", "Grapes", "Guava"]

Slice creates a new array, copies elements from index start till the end (not inclusive)

let arr = ["A", "B", "C", "D"];

alert( arr.slice(1, 3) ); 
// B,C (copy from 1 to 3)

alert( arr.slice(-2) );
// C,D (copy from -2 till the end)

I hope you found this to be helpful. I've categorized it simply so that you can quickly understand the ideas. These are the fundamentals. If you do some exploration, you'll discover more Array Methods.