Arrays in Javascript

Javascript

Created: 2022-10-20


Length of Array

const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
console.log(shopping.length);  // 5

Modifying Values in Array

const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
shopping[0] = 'tahini';
console.log(shopping);
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]

Find the index of a value

const birds = ['Parrot', 'Falcon', 'Owl'];
console.log(birds.indexOf('Owl'));   //  2

Adding items to an array

const cities = ['Manchester', 'Liverpool'];
cities.push('Cardiff'); // adds at the END
cities.unshift('Edinburgh');  // adds at BEGINNING
cities.pop('Liverpool');