Skip to main content

Command Palette

Search for a command to run...

Array in Js

Updated
7 min read
Array in Js

Hello readers....

Welcome back to another blog. This is my 4th blog of this js series. Till now, what we have covered:

  1. Variables & Data Types Overview

  2. JS Operators

  3. If else & switch statement

In this blog, I'm going to write about the array. Yes, the Non-Primitive data type.

The Problem: When Variables Become Chaos

In my first blog, I have explained that the variables are the container which keeps values.

let student1 = "Abhishek"
let student1 = "Harah"
let student2 = "Sumit"
let student3 = "karan"
let student4 = "umar"

Fine.... Right

Now, imagine if you have to store 500 students' data

Isn't it too chaotic to create 500 variables for each student? Problem you will face:

  1. It is very tough to create those 500 variables and assign values to each of them.

  2. Managing those 500 variables is another nightmare.

  3. Accessing and updating those variables is another level of the problem.

  4. As the number of student increase, you will have to create new variables and assign students' data.

Now you can say, creating a variable for each data is not good, and it can be very chaotic.

That's why we have arrays to save us from this chaos.

The hero of the story: Array

An array is a non-primitive data type in JS that allows you to store multiple values in a single variable.

So instead of creating 500 variables, we can do this :

let students = ["Abhishek", "Rahul", "vivek","sumit", "jani", ...... "Karan", "umar"]
console.log(students)

Here are the properties of an array in js:

  1. Arrays store values in contiguous form in the heap, which makes it flexible and dynamic in size.

  2. In a JS array, you can keep any type of data, like numbers, strings, array itself, objects, and others too.

  3. The type of array in JS is Object.

  4. It's easy to add, delete, update, or access values of an array.

  5. Js array have too many methods, which makes the above operation super easy.

Ways to declare an array

  1. Using array literals (most common)

In this method, you keep all your values inside the square brackets. Here is an example

const data = [1,null,"abhishek"]
  1. Using the array constructor

We can create an array using the Array constructor.

Example:

const data = new Array(1, null, "abhishek")

Accessing array elements

To access the array elements, we use indexing, and array indexing starts with 0

Example:

const data = new Array(1, null, "abhishek")
data[0] //1 is at 0th index of array
data[1] //null is at 1st index of array
data[2] //abhishek is at the 3rd or last index of the array

Why 0-based indexing?

In js or some other languages also uses 0 based indexing because it makes the address calculation easy. Let me explain

Suppose there are three elements in the array, and each has 4 byte size.

const data = [1,2,"3"]

Let's assume the address of each element

Element Index Address
1 0 1000
2 1 1000+4 = 1004
"3" 2 1004+4 = 1008

To find the next address, JS uses this formula:

Formula: starting address+(index X size)

Eg: 1000+(0X4) = 1000
    1000+(1X4) = 1004
    1004+(2X4) = 1008

Now imagine if the index starts with 1, then the formula will look like this:

Formula: starting address+((index -1) X size)

You can notice that extra -1, that's why most languages uses 0 based indexing to make the next address calculation easy.

Array Modification

Now you know the indexing, so you can also modify the particular index value. Here is an example:

const data = ["abhishek", "karan", "sumit", "umar"]

console.log("value before change: ", data);

//change index - 2 data to Harsh
data[2] = "Harsh"

//now the index-2 value is changed
console.log("value after change: ", data);

Length property

Arrays also have a length property, which gives you the count of total elements inside that array.

const data = [1,2,3,4,5]
console.log(data.length) //5

In the above example, there are a total of 5 elements in the array, so you will get 5 as the answer.

The length property is also used to change the size of an array. Here is an example

const data = [1,2,3,4,5]
console.log(data) //[1,2,3,4,5]

data.length = 2
console.log(data) //[1,2]
console.log(data.length) //2

In the above example, we initiated the array with 5 elements, but when we set the length to 2, our array size was reduced to 2, and the rest of the elements got deleted.

💡
To get the last element of the array, use data. length - 1 due to 0-based indexing

Iterating over array values

Well, we can access the values of an array using the index, like this:

let students = ["Rahul", "Aman", "Neha", "Riya", "Kunal"];
console.log(students[0]);
console.log(students[1]);
console.log(students[2]);
console.log(students[3]);
console.log(students[4]);

which is totally fine.

Now, imagine the array contains 500 students.

Would you write 500 console.log statements?

Of course not.

This is where iteration becomes important.

What is iteration?

Iteration means keep processing till a condition is met. That's it.

In the context of an array:

Going through each element of an array one by one.

As we have written each line manually, we will iterate (run a loop) through the array.

There are multiple ways to iterate through an array, but the most common loops are:

  1. For loop

  2. While loop

  3. Do while loop

  • For Loop

This is the most common loop to iterate over an array. It takes:

  1. initial value (optional)

  2. condition (required)

  3. afterthought (optional)

for(initial value; condition; afterthought){
//your code
}
💡
Optional means you can initialize the value earlier, and you can also put the afterthought inside the for loop block, but the semicolons are necessary.

Here is an example of a for loop:

  1. In the first example i'm initializing i with 0 and giving a condition that it should be less than the array length, and at the end passing the afterthough which is incremented by 1.

  2. Second is also the same, but initializing the value outside the for loop and giving the afterthought inside the for loop block.

Both are correct.

  • While Loop

A while loop is another way to iterate. In this loop, we use the while keyword and pass the condition. As long as the condition is true, our while loop runs. Inside the while loop block, we include the afterthought, which helps to exit the loop or make the passed condition false.

syntax:

while(condition){
    //code
    // afterthought is required otherwise it will run infinite.
}
💡
This is quite similar to the second example of a for loop, right? So if you have to pass the condition only and your value is initialized before, then use while instead of for.
  • do while loop

This is the third way of iterating over an array. This loop runs at least once, then it checks the condition, if the condition is true, then it run furhter.

syntax:

do {
  // loop body
} while (condition)

The loop will first execute the body, then check the condition, and while it remains truthy, it will execute the body again and again.

That’s it for this blog.

In the next blog, we will explore something even more interesting. JavaScript arrays provide many built-in methods that make working with arrays much easier and more powerful.

Also, there are other ways to iterate over arrays in JavaScript. In this blog, we only covered the basic iteration methods.

In the next one, I will discuss array methods and other ways to iterate through arrays.

Till then,

Keep reading, keep building.

Bye 👋