Introduction to Array in Javascript

Introduction to Array in Javascript

In this blog, we are going to explore Arrays in Javascript

·

2 min read

What is Array?

An array is a special object in Javascript, that stores multiple values inside a single variable.

Why is Array needed?

Let’s take a scenario where we need to store multiple variables ranging up to 100(i.e., we need to keep 100 variables). Usually, what we will

Var a = 10;
Var b =30;
Var c = 40;
.
.
.
.
.
.
.
.
.
.
.
It goes on

In the above case, there is a lot of memory space is wasted and it’s not possible to store 100 variables in the above manner it creates issues in dynamic data storage also. So, the Array concept gives a solution to this problem. Because with the array we can store multiple values inside a single variable.

How to create an Array?

We use Square brackets(i.e., []) to enclose the array of elements inside a single variable.

Example:-

let arr = [ 1, 2, 3, 6,7 ];

How to access array elements?

We can access an array of elements by using its index value.

Let’s take an example,

let arr = [1,2,3,4,5];

In the above example, if we need to access the fourth element of the array. We will access it by its index value.

The Index value starts with 0 and it goes on.

HTML (4).png

The above picture shows the array of elements with its index value.

So, if we need to access fourth element of the array. We will do it by

console.log(arr[3]); // 4

Methods for defining array:

We can define an array in two methods, are

The first method is the regular method to define an array,

let arr = [ 1, 2, 3, 4 ];

The Second method is,

Step-1: First declare an empty array.

let arr = [];

Step-2: Next, using its index value - insert elements one after another.

arr[0] = “Banana”;
arr[1] = “Apple”;
arr[2] = “orange”;
console.log(arr); // [ “Banana”, “Apple”, “orange”];

In the next blog, we will explore array properties and methods.