Everything about Arrays in JavaScript💻

Everything about Arrays in JavaScript💻

Introduction

In most programming languages, array serves as an inbuilt data structure to store data in an orderly fashion, so is the case with JavaScript but with a little tweak. Array in JavaScript is actually Array object, as the name suggests, the array is built on top of objects just as literally everything else in JS.
Wait but what is an object?
Well, object in JS is nothing but a way to store data in a key-value pair, like

myObj = {
  key: "value"
};

So we have a way to store data in JS in form of objects, then why do we need arrays in the first place?
The answer to this lies in the object capabilities. While objects can store data but that is not an ordered collection and in most cases this is what we need to deal with programming problems- an ordered collection. As objects provide no methods to manage the order of elements, we simply cannot insert something in between or so. These all leads to the undoubted need of Arrays in JS.

Declaration of Arrays

An empty array can be declared in JS in following two ways:

let myArr = new Array();
let myArr = [];

Most usually, the second way is used for declaration.

An empty array can be populated using data by simply putting them inside the square brackets enclosed in single or double quotes separated by commas if string and without qoutes otherwise, like

let myArr = ["learncodeonline", "ineuron", "javascript"];
let num = [1, 2, 3];

How is Array in JS different from other static typed programming languages?

Arrays in JS are infact quite dissimilar from conventional arrays in programming languages like C, C++ or Java.

Some of the differenced are listed below:

  • Arrays in JS are not fixed in length like arrays in C or C++.
  • Arrays in JS can contain any data type be it number, string or boolean unlike arrays in other programming languages where any single data typed values can be stored.

Accessing the elements in Arrays

The elements of an array are numbered starting with zero, i.e, zero-indexed.

Arrays.drawio.png

  • The length of an Array can be found using length property, like
    const arrLength = myArr.length;
    
  • To access an element of an array using its non-negative index, simply use,

    const  firstElem = myArr[0] //accessing the first element of the array
    
  • All elements of an array can be accessed through an for loop, for example,

    for(let i=0; i<myArr.length; i++){
    console.log(myArr[i]);
    }
    
  • Some programming languages allow using negative indexes to access the elements from the last of an array, but in JavaScript, this is not possible because negative indexes are not allowed to be used directly with the array variable name, like myArr[-1] //error. To solve this problem we use at method. For example
    const lastElem = myArr.at(-1);
    

Push, Pop, Shift and Unshift

Using some methods, we can control the edge elements of an array, i.e., first and last elements of the array.

  • push method: This method append the element to the end of the array.
    let arr = ["js", "python"];
    arr.push("rust");
    console.log(arr); // ["js", "python", "rust"]
    
  • pop method: This method removes the last element of the array and returns it.
    let arr = ["js", "python", "rust"];
    arr.pop();
    console.log(arr); // ["js", "python"]
    
  • shift method: This method removes the first element of the array and returns it.
    let arr = [1, 2, 3, 4];
    arr.shift();
    console.log(arr); // [2, 3, 4]
    
  • unshift method: This method adds the element at the beginning of the array.
    let arr = [2, 3, 4];
    arr.unshift(1);
    console.log(arr); // [1, 2, 3, 4]
    

Converting Array into String

  • toString(): This method converts the array into a string.
    let arr = ["I", "am", "Raushan"];
    let stringArr = arr.toString();
    console.log(stringArr); // I,am,Raushan
    
  • join(): This method also works the same way as the toString() method, but we can also specify the separator with this method.
    let arr = ["I", "am", "Raushan"];
    let stringArr = arr.join("*");
    console.log(stringArr); // I*am*Raushan
    

Merging arrays

With concat() method we can concatenate a array with another. Note, the concatenation results into the formation of a new array.

let n = [1, 2, 3];
let m = [4, 5, 6];
let x = n.concat(m);
console.log(x) // 1, 2, 3, 4, 5, 6

Modifying the Array

With slice() and splice() methods, we can change and alter the order and elements inside an array.

  • slice() method: This method, as the name suggest, slices the elements of an array and returns it into a new array.
    let n = [1, 2, 3];
    let x = n.slice(1);
    console.log(x) // 2, 3 ~ slices the array n from index number = 1 to the last
    
  • splice() method: This method is in a way similar to the above slice() method, but with this method, we can also insert some elements in between.
let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2, 2, "March", "April");
//starts from the index number = 2, removes 2 elements, appends the argument strings.

console.log(days); // ["Monday", "Tuesday"]
console.log(months); // ["January", "February", "March", "April"]

Checking if an element exists

To check if an element exists in an array, we can use includes(). If exists, the function will return true, otherwise false.

let a = [1, 2, 3, 4];
console.log(a.includes(1)); //true
console.log(a.includes(8)); //false

Checking the index of an element

To check the index of an element in an array, we can use indexOf(). If the element does not exist, the function will return -1.

let a = [1, 2, 3, 4];
console.log(a.indexOf(1)); // 0
console.log(a.indexOf(8)); // -1

There is another useful method called lastIndexOf(), which returns the index of the last occuring element specified in the argument.

let a = [1, 2, 1, 2, 5, 4 ,2];
console.log(a.lastIndexOf(2)); //6

Sorting an Array

To sort an array, we use sort() method

let a = [5, 4, 9, 7, 3, 2];
console.log(a.sort()); // 2, 3, 4, 5, 7, 9

Reversing an Array

To reverse an array, we use reverse() method

let num = [1, 2, 3, 4, 5, 6];
let reversedNum = num.reverse();
console.log(reversedNum);// 6, 5, 4, 3, 2, 1

I think that this much information about Arrays is what your require to master in JavaScript. For more powerful methods, I would recommend
javascript.info

#iwritecode #lco #ineuron #webdev