Arrays in JavaScript

Arrays in JavaScript

Play this article

Table of contents

The array is like a big container into which we can throw variables and later use them. It helps us to store multiple elements in a single variable using a single variable name. In JavaScript Array isn’t primitive, it’s an object.

Basic Array Operations and syntax

Creating an array :

const pets = ['Bruno' , 'Buddy' , 'Kuki' ]; 
//or we can also do,
const num = new Array (12 , 13 , 14) ;

To retrieve elements :

console.log(pets); //prints the whole array
console.log(pets[0]); //prints the first element , arrays are zero based

The .length property :

console.log(pets.length);  //prints 3 , length is calculated from 1 not 0
console.log(pets[pets.length-1]); //prints the last element of the array

We can also mutate the array using [ ],

pets[0] = 'Snowy'
console.log(pets); // 'Snowy' , 'Buddy' , 'Kuki'

Arrays also can store variables,

const firstName = 'Debasish'
const fullName = [ firstName , “Lenka” ]// prints Debasish Lenka

We can also include an array inside of an array,

const bio = [fullName , 'Job: Developer 🧑🏻‍💻'];


**0**: (2) ['Debasish', 'Lenka']
**1**: "Job: Developer 🧑🏻‍💻"
**length**: 2

push method(adds element to end of the array):

const boys = ['Biki','Gudu','Raj'];
console.log(boys) // 'Biki' , 'Gudu' , 'Raj' , 'Jay'

/*push function also reyturns the length of the new array. if we store the above push
function in a const and try to capture it */

const pushed = boys.push('Jay') 
console.log(pushed); // returns 4

unshift method(adds to the beginning of the array):

console.log(boys); // 'John' , 'Biki' , 'Gudu' , 'Raj' , 'Jay'

pop method (Remove element from end) :

console.log(boys); // 'John' , 'Biki' , 'Gudu' , 'Raj'

shift method (Remove element from beginning) :

console.log(boys); // 'Biki' , 'Gudu' , 'Raj'

indexOf method tells us in which position a certain element is in the array :

console.log(boys.indexOf('Biki')); // 0
console.log(boys.indexOf('Sky')); // -1

includes method (returns true if the element is present in the array and false if the element is not present in the array):

console.log(boys); // 'Biki' , 'Gudu' , 'Raj' , 2023
console.log(boys.includes('2023'));//false //because it's testing with strict equality and doesn't do Type Coercion

Array.reverse() :

const boys = ['Biki' , 'Gudu' , 'Raj'];
// output: 'Biki' , 'Gudu' , 'Raj'

const reversed = boys.reverse();
// output: 'Raj' , 'Gudu' , 'Biki'

// reverse is destructive , it changes the original array.
// output: 'Raj' , 'Gudu' , 'Biki'


There are a lot of other methods in JavaScript and we can always refer to MDN for the same ✨. I hope you found this article useful, if you need any help or want to give any suggestions please let me know in the comment section.

Feel free to contact me.

Did you find this article valuable?

Support Debasish Lenka by becoming a sponsor. Any amount is appreciated!