DEV Community

Cover image for Understanding Arrays in JavaScript for Beginners
Soubhagya Dash
Soubhagya Dash

Posted on

Understanding Arrays in JavaScript for Beginners

Today, we’re going to learn why arrays are needed, what arrays are, and how to loop through them.

So, let’s get started with why arrays came into JavaScript in the first place.

Imagine you have to store marks of some students in your batch. Imagine arrays didn’t exist, how would you store multiple marks?
Probably like this:-

let mark1 = 87
let mark2 = 69
let mark3 = 92
.
.
.
let markn = 56
Enter fullscreen mode Exit fullscreen mode

These codes already seem full of verbosity. Now, imagine that you have 100 or more students. What would you do then?

You probably wouldn’t want to repeat the above process 100 or more times. To solve this problem, JavaScript introduced arrays.

What is an array?

An array is a data structure that allows us to store multiple values together under a single variable. Or you can say it is a collection of values stored in order.

Instead of writing those verbose codes, we can create an array like this:-

let marks = [87, 69, 92, 78, 56]
Enter fullscreen mode Exit fullscreen mode

Each value stored inside an array is called an element. So, each element can be any data type (string, number, boolean...).

let random = [51, "hyyy", true, null, undefined]
Enter fullscreen mode Exit fullscreen mode

We can access each element inside the array using its index.

So, here a question arises: what is an index?

Inside an array, each element has an individual position where we can access an element. These positions are called indexes of an array.
So, in JavaScript, indexing of an array starts from 0.

Let's look for an example how can we access an element using it's index.

let marks = [87, 69, 92, 78, 56]
console.log(marks[1])                     // 69
Enter fullscreen mode Exit fullscreen mode

We can see how many elements there are in an array using the length property. To use the length property, simply write it like this:

let marks = [87, 69, 92, 78, 56]
let elementCount = marks.length ;
console.log(elementCount)                     // 5
Enter fullscreen mode Exit fullscreen mode

Even if we store an array in a variable, we can still add and make changes to it.

we can update an element right after we stored it.

let marks = [87, 69, 92, 78, 56]
marks[2] = 46;
console.log(marks)                     // [87, 69, 46, 78, 56]
Enter fullscreen mode Exit fullscreen mode

Imagine, you have an assignment to print all the elements in an array. You may do something like this :-

let marks = [87, 69, 92, 78, 56]
console.log(marks[0])
console.log(marks[1])
console.log(marks[2])
console.log(marks[3])
console.log(marks[4])
Enter fullscreen mode Exit fullscreen mode

Isn’t it a problem to print all the elements one by one? Imagine there are 100 elements in an array. Are we going to print all 100 elements one by one?

We run into the same problem again. To solve this problem, we use loops.
So, let’s talk about some loops that help us go through the elements of an array.

  1. for loop
  2. while loop
  3. do...while loop
  4. for...of loop

for loop

A for loop is used when you want to repeat a block of code multiple times. This is the most usable loop in javascript.

The basic syntax of for loop is :-

for (initialization; condition; update) {
    // code to repeat
}
Enter fullscreen mode Exit fullscreen mode

Let's take an example of for loop:-

let marks = [87, 69, 92, 78, 56]

for (let i = 0; i < 5; i++) {
    console.log(marks[i])
}

// 87
// 69
// 92
// 78
// 56
Enter fullscreen mode Exit fullscreen mode

Let’s understand how it works with a quick dry run:-

i Condition (i < 5) console.log(marks[i]) i++ / Update
0 0 < 5 (true) 87 1
1 1 < 5 (true) 69 2
2 2 < 5 (true) 92 3
3 3 < 5 (true) 78 4
4 4 < 5 (true) 56 5
5 5 < 5 (false) --- ---

Here the code will process 6 times but the code will print 5 times.

Basically,

Use this loop when you exactly know how many times you want the code to run.

How a for loop works:-

  1. i = 0
    Here, i represents the index of the array. We start the loop from index 0, because array indexing starts from 0.

  2. i < 5
    Here, we give a condition that tells the loop when to continue. The loop will continue as long as the value of i is less than 5.

  3. i++
    Here, we use the increment operator to increase the value of i by 1 after each iteration. If we don't update i, its value would always remain the same, and the loop could continue forever.

Execution of the loop:-

First, the loop starts with i = 0. Then, it checks whether the condition is true or false. If the condition is true, the code inside the block scope is executed. After that, i gets updated using i++, and the loop starts again. This process continues until the condition becomes false.

While loop

A while loop is also used when you want to repeat a block of code as long as a condition is true.

The basic syntax of while loop is :-

while (condition) {
    // code to execute
}
Enter fullscreen mode Exit fullscreen mode

Let's take an example of while loop:-

let marks = [87, 69, 92, 78, 56]

let i = 0
while (i < marks.length) {
    console.log(marks[i])
    i++;
}

// 87
// 69
// 92
// 78
// 56
Enter fullscreen mode Exit fullscreen mode

Basically,

Keep running the code untill the task in complete

You can think it as:-

I only know the condition but don't know how may iterations.

Execution of the loop:-

Mainly, we have to declare a variable with the starting index number outside the loop. First, the loop starts by checking the condition. If the condition is true, the code inside the block scope is executed. After that, the value of i is updated using i++, and the loop checks the condition again. This process continues as long as the condition is true. When the condition becomes false, the loop stops.

do...while loop

The do...while loop is used when you want the code to run at least once, and then check the condition.

The basic syntax of do...while loop is :-

do {
  // code to execute
} while (condition);
Enter fullscreen mode Exit fullscreen mode

Let's take an example of do...while loop:-

let marks = [87, 69, 92, 78, 56];

let i = 0;         // index
do {
    console.log("this is a number: " + marks[i]);
    i++;
} while (i < marks.length);


// this is a number :87
// this is a number :69
// this is a number :92
// this is a number :78
// this is a number :56
// this is a number :undefined
Enter fullscreen mode Exit fullscreen mode
i console.log(marks[i]) i++ / Update Condition (i <= 5)
0 87 1 1 <= 5 (true)
1 69 2 2 <= 5 (true)
2 92 3 3 <= 5 (true)
3 78 4 4 <= 5 (true)
4 56 5 5 <= 5 (true)
5 undefined 6 6 <= 5 (false)

Basically,

It'll run at least one time, even if the condition is false.

Execution of the loop:-

First, we initialize i with the starting index number (0). JavaScript enters the do block and accesses marks[i]. Since i is 0, it prints the first element (87). After each iteration, i is increased by 1, so JavaScript moves to the next index and prints the next element. This continues until i becomes 5. At this point, marks[5] is undefined because the array only has indexes from 0 to 4. After that, i becomes 6, and JavaScript checks i < marks.length --> 6 < 5, which is false, so the loop stops.

for...of loop

for...of lets you directly get each value one by one without worrying about the index.

The basic syntax of while loop is :-

for (let variable of iterable) {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Let's take an example of while loop:-

let marks = [87, 69, 92, 78, 56]

for (const mark of marks) {
    console.log(mark)
}

// 87
// 69
// 92
// 78
// 56
Enter fullscreen mode Exit fullscreen mode

How a for...of loop works:-

  1. Here you don't have to worry for initialization, condition or an update. for...of loop goes direct through each elements in an array.
  2. Here mark is the variable we declared directly that stores the current value of the array.
  3. we've to put the array name that we want to iterate in place of iterable.
  4. of tells javascript to take the value from marks.

Execution of the loop:-

First, the for...of loop takes the first value from the array and stores it in the declared variable (mark). Then, the code inside the block scope is executed. After that, the loop automatically takes the next value from the array and executes the code again. This process continues until there are no more values left in the array, and then the loop stops.

_______________________________ X _______________________________

And that's a wrap!
Today, we explored arrays in JavaScript, learned how to work with them, and saw how loops can help us easily go through the elements.

This is just the beginning—there's a lot more to explore with arrays!

That’s it for Today! It was a good learning session. Now, time to move on to the next concept.✌️

Top comments (0)