view all posts

Understanding basics of array in javascript

Frugence | 6 months ago

In the post i will share some basics about Array.

Array is the way of storing group or list of data.

Let say, we want to store group of colors without using array.
    const color1 = 'purple';
    const color2 = 'black';
    const color3 = 'yellow';
    const color4 = 'aqua';
As we see, our codes are not DRY(Don't Repeat Yourself) at all. They are WET(Write Everything Twice), this is not a good practice for writing good code. We can use Array to solve this problem.
    const colors = ['purple', 'black', 'yellow', 'aqua'];
How to create Array

You can start with empty Array and then add data later, or you can start with it's data;
    // empty array
    const colors = [];

    // with data
    const colors = ['purple', 'black', 'yellow', 'aqua'];
Add data into array

There two way I known for adding data into the Array, 'bracket notation' and array methods.

i. By bracket notation

Array are indexed starting from 0.
    const colors = [];

    // Add first data
    colors[0] = 'purple';

    // So the second item
    colors[1] = 'black';

    console.log(colors); // ['purple', 'black'];
ii. By Array methods

If you want to add item at very first position of Array use unshift method, at very end use push method.
    const colors = ['purple', 'black'];

    // use unshift method to add to front
    console.log(colors); // ['aqua', 'purple', 'black'];

    // use push method to add to end
    console.log(colors); // ['aqua', 'purple', 'black', 'yellow'];    
Access data from Array

You can access data from Array by using bracket notation.
    const colors = ['purple', 'black', 'yellow', 'aqua'];

    // black and aqua
    colors[1]; // 'black'
    colors[3]; // 'aqua'
Also you can access array's item by loop over it.
    const colors = ['purple', 'black', 'yellow', 'aqua'];

    for(const color of colors) {
      console.log(color);  // purple black yellow aqua
Update data of Array

Also you can use bracket notation to update array's data.
    const colors = ['purple', 'black'];

    // update black to yellow
    colors[1] = 'yellow';
    console.log(colors); // ['purple', 'yellow'];
Array can hold any data type and can be nested.
    const data = [24, true, ['orange', null], undefined];