Table of contents
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); //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 = '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 🧑🏻💻']; console.log(bio);
**0**: (2) ['Debasish', 'Lenka'] **1**: "Job: Developer 🧑🏻💻" **length**: 2
push method(adds element to end of the array):
const boys = ['Biki','Gudu','Raj']; boys.push('Jay'); 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):
boys.unshift('John'); console.log(boys); // 'John' , 'Biki' , 'Gudu' , 'Raj' , 'Jay'
pop method (Remove element from end) :
boys.pop(); console.log(boys); // 'John' , 'Biki' , 'Gudu' , 'Raj'
shift method (Remove element from beginning) :
boys.shift(); 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):
boys.push(23); console.log(boys); // 'Biki' , 'Gudu' , 'Raj' , 2023 console.log(boys.includes(2023));//true console.log(boys.includes('2023'));//false //because it's testing with strict equality and doesn't do Type Coercion
const boys = ['Biki' , 'Gudu' , 'Raj']; console.log(boys); // output: 'Biki' , 'Gudu' , 'Raj' const reversed = boys.reverse(); console.log(reversed); // output: 'Raj' , 'Gudu' , 'Biki' // reverse is destructive , it changes the original array. console.log(boys); // output: 'Raj' , 'Gudu' , 'Biki'
Feel free to contact me.