Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Updated
2 min readView as Markdown
JavaScript Arrays 101

Array is the group of values to store in single variable, till now we store single value in the variable, but what if we have group of values like fruits or friends,

Simple variables

let friend1 = "Hitesh"
let friend2 = "Piyush"
let friend3 = "Anirudh"
let friend4 = "Jai"
let friend5 = "Jags"

But with Arrays

let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]
// single group of collections of the list

Accessing Elements

with index we can acces the values like:

Index starts with 0

// index           0       1        2        3      4
let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]

//print values (Access values)

console.log(friends[0]) // Hitesh
console.log(friends[2]) // Anirudh

Updating values

yes, we can update values from the list like:

let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]

friends[2] = "Big Boss"

//now array will be
console.log(friends) 
// ['Hitesh', 'Piyush', 'Big Boss', 'Jai', 'Jags']

Array Length (count value of the arrays)

let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]
// count the values of the arrays
console.log(friends.length) // 5

Looping Over Arrays

If you want do some action or any calculation use for of loop

let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]
// count the values of the arrays
for (let friend of friends ) {
  console.log(friend + ' is my Friend');
}
// Hitesh is my Friend
// Piyush is my Friend
// Anirudh is my Friend
// Jai is my Friend
// Jags is my Friend

Summary

Array is the collection of values in a variable. it could be string, number, boolean all of the values can be

  • we can create array with []

  • Array can acccess with index like myArray[index]

  • Array can be updated with index and assgin value like myArray[index] = newvalue

  • Array can loop with for of loop

let movies = ["Movie1", "Movie2", "Movie3", "Movie4", "Movie5"];

console.log(movies[0]); // Movie1

movies[2] = "Movie2";

for (movie of movies) {
  console.log(movie);
}