Home Courses Array Tutorial for Beginners - Array Definition, Operations

Array Tutorial for Beginners - Array Definition, Operations

An array is used when you want to store multiple values inside one variable.

For example, if you have a list of users, products, or students, instead of creating many variables, you can store everything inside one array.


Why Do We Use Arrays?

If you use a normal variable, you can store only one value at a time.

But with an array, you can store many values together, and manage them easily.


How to Create an Array

There are two ways to create an array.

First way (less used):


let users = new Array("anil", "sam", "sidhu");

Second way (most common and recommended):


let users = ["anil", "peter", "sam", "sidhu"];


How to Access Values

Array always starts from index 0.


console.log(users[0]); // anil
console.log(users[1]); // peter

So remember, first value is at index 0, not 1.


How to Update a Value

If you want to change a value:


users[2] = "bruce";
console.log(users);

Now "sam" will become "bruce".


How to Add a New Value

To add a new value at the end:


users[users.length] = "tony";

This automatically adds the value at the last position.


How to Check Total Elements

To find how many values are inside the array:


console.log(users.length);


How to Delete a Value


delete users[2];

But this does not completely remove the value. It makes it undefined and keeps empty space.


Loop Through Array

If you want to print all values, you can use a loop.

Using for loop:


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


Using for...of loop (easy way):


for(let item of users){
console.log(item);
}


Share this lesson: