Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Today we will understand about arrays, what is array & why need this ?

Updated
3 min read
JavaScript Arrays 101

When we start programming usually we store value in a variable, like bellow

let fruit1="Apple";
let fruit2="Banana";
let fruit3="Orange"

that's fine with few value but just imagine if we have 50 or 100 of values??

Then this work will be very difficult to manage and time taking.

This is where Array helps us.

Array help us to store multiple value in a single variable with organized order.

What is an Array?

An Array is a collection of values store in order inside a variable.

Example

let fruits = ["Apple", "Banana", "Orange"];

Here:

  • fruits is the Array name

  • It's store multiple values

  • each values called elements

How to create an Array ?

In JavaScript Array created by square brackets []

Another Example

let marks = [85, 90, 78, 92];

Arrays can store different type of values in a single array but we normally store similar type at once.

Array Index

Each Array's elements have their own position that called an index.

Each index number of Arrays start with Zero (0), not one (1)

Example

let fruits = ["Apple", "Banana", "Orange"];

index of 0 -> Apple

index of 1 -> Banana

index of 2 -> Orange

How to target Array Elements?

The Bracket Notation ([]) is the most common method to access any elements with positive index number.

Example

let fruits = ["Apple", "Banana", "Orange"];

console.log(fruits[0]) // Apple
console.log(fruits[1]) // Banana
console.log(fruits[2]) // Orange

Here we are telling JavaScript:

"Give me the value stored at this position."

What is Array's Length Property?

Array have a built-in property called length . It's tell us how many elements are store inside that Array.

Example

let fruits = ["Apple", "Banana", "Orange"];

console.log(fruits.length); // output -> 3

That means we have 3 element in fruits Array.

Let's try to manipulate a new Array!! ( assignment )

  1. Let's we have 5 movies name in moviesName Array
let moviesName = ["Dangal", "3 Idiots", "Sholay", "PK", "Lagaan"];
  1. we can easily print first and last element
let moviesName = ["Dangal", "3 Idiots", "Sholay", "PK", "Lagaan"];

console.log(moviesName[0]) // output -> Dangal
console.log(moviesName[moviesName.length-1]) // output -> Lagaan
  1. We can change any element like bellow
let moviesName = ["Dangal", "3 Idiots", "Sholay", "PK", "Lagaan"];

moviesName[1]="Swades"

console.log(moviesName);//[ 'Dangal', 'Swades', 'Sholay', 'PK', 'Lagaan' ]
  1. We can print each value separately
let moviesName = ["Dangal", "3 Idiots", "Sholay", "PK", "Lagaan"];

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

Output will be ->

Dangal
3 Idiots
Sholay
PK
Lagaan

Why Arrays Are Useful?

  1. cleaner

  2. easy to write

  3. easier to manage

  4. easier to loop through

Thank you for Read Patiently