Arrays in Javascript

Arrays in Javascript

ยท

6 min read

Introduction

Arrays are an ordered collection of items/elements. In Javascript, these elements can be of any data type. In Js, array is an object. Array is one of the most important data structures in javascript.

Creating an array

We can create an array in this way ๐Ÿ‘‡

// An array containing strings
const fruits = ["apple", "mango", "grapes"];

// An array containing numbers
const numbers = [1, 2, 3, 4];

// An array containing different datatypes
const arr = [1, 2, 3.2, "string", null, undefined];

Another way of creating an array:-

const fruit = new Array("apple", "mango", "grapes");

Accessing the elements of an array

Arrays elements are ordered by index values starting from 0. So they can be accessed by those index values.

  • The first element gets an index of 0
  • The second element gets an index of 1.
  • The third element gets an index of 2.
  • Similarly, the nth element will have an index value of n-1.
const fruits = ["apple", "mango", "grapes"];

console.log(fruits[1]);  // mango

Changing the value of an array element

We can change the value of an array element by accessing the element and assigning a new value to it.

const fruits = ["apple", "mango", "grapes"];

fruits[1] = "banana";

console.log(fruits[1]);  // banana

console.log(fruits);  // ["apple", "banana", "grapes"]

This signifies that, unlike strings, array is mutable as the original array is getting changed.

Array Methods

isArray()

isArray() helps to determine whether the passed value is an array.

const fruits = ["apple", "mango", "grapes"];

console.log(typeof fruits);  // object

So if we check the typeof of an array it shows to be an object. That's why we say that in javascript, array is an object.

Now, to check whether the passed value is an array we do this ๐Ÿ‘‡

console.log(Array.isArray(fruits));  // true

push()

push() method adds one or more new elements at the end of an array and returns the new length of the array.

const fruits = ["apple", "mango", "grapes"];

fruits.push("banana");

console.log(fruits);  // ["apple", "mango", "grapes", "banana"]
console.log(fruits.push());  // 4

pop()

push() method removes an element from the end of an array.

const fruits = ["apple", "mango", "grapes"];

console.log(fruits.pop());  // grapes

console.log(fruits);  // ['"apple", "mango"]

unshift()

unshift() method adds one or more new elements at the beginning of an array and returns the new length of the array.

const fruits = ["apple", "mango", "grapes"];

fruits.unshift("banana");

console.log(fruits);  // ["banana", "apple", "mango", "grapes"]
console.log(fruits.unshift());  // 4

shift()

shift() method removes an element from the beginning of an array.

const fruits = ["apple", "mango", "grapes"];

console.log(fruits.shift());  // apple

console.log(fruits);  // ["mango", "grapes"]

push-pop is faster than shift-unshift because shift-unshift removes or adds elements at the beginning of the array for which all the other element's position gets shifted which is expensive and consumes more time as well. Whereas push-pop adds or removes element from the end of the array for which no other element's position gets affected. For this reason, push-pop is much better, faster, and cost-effective.

Array is a reference type variable

Arrays are always reference type variables. To understand this we need to first understand primitive type variables:-

// Primitive type

let num1 = 3;
let num2 = num1;

console.log("value of num1 is", num1);  // 3
console.log("value of num2 is", num2);  // 3

num1++;

console.log("value of num1 is", num1);  // 4
console.log("value of num2 is", num2);  // 3

Here num1 and num2 got stored in the stack memory where both the variables will get separate memory spaces with the same value stored in them. Both are not linked with each other. So change in the value of one variable will not affect the other.

primitive.png

Now let's understand the reference type variables:-

// Reference type

let array1 = ["item1", "item2"];
let array2 = array1;

console.log("array1", array1);  // ["item1", "item2"]
console.log("array2", array2);  // ["item1", "item2"]

array1.push("item3");

console.log("array1", array1);  // ["item1", "item2", "item3"]
console.log("array2", array2);  // ["item1", "item2", "item3"]

Here value gets stored in the heap memory and the variables array1 and array2 are stored in the stack memory. array1 = ["item1", "item2"] means that variable array1 will point to the address(1x11) in the heap memory where the value ["item1", "item2"] is stored. So, array2 = array1 simply means that array2 will point towards the same address(1x11) where array1 is pointing. So, if any changes in the value occur then it will get reflected on both the variables as they are only pointing towards the address(1x11) which contains the value.

reference.png

If both the array values are the same that doesn't mean that both of them are equal


let array1 = ["item1", "item2"];
let array2 = ["item1", "item2"];

console.log(array1 == array2);  // false

This happens because both arrays are pointing towards different addresses.

address.png

Array cloning

We can clone an array using the following ways ๐Ÿ‘‡

let array1 = ["item1", "item2"];

// First way
const array2 = array1.slice(0);

// Second way
const array2 = [].concat(array1);

// Third way
const array2 = [...array1];

Array concatenation

We can concatenate an array using the following ways ๐Ÿ‘‡

const array1 = ["item1", "item2"];

// First way
const array2 = array1.slice(0).concat(["item3", "item4"]);  // ["item1", "item2", "item3", "item4"]

// Second way
const array2 = [].concat(array1, ["item3", "item4"]);  // ["item1", "item2", "item3", "item4"]

// Third way
const array2 = [...array1, "item3", "item4"];  // ["item1", "item2", "item3", "item4"]

for of loop - array

The for of loop iterates through the values of an iterable object, here array.

const fruits = ["apple", "mango", "grapes", "banana"];

for(let fruit of fruits) {
    console.log(fruit);
}

/*Output:-
  apple
  mango
  grapes
  banana
*/

for in loop - array

The for in loop iterates through the properties of an object, here array.

const fruits = ["apple", "mango", "grapes", "banana"];

for(let index in fruits) {
    console.log(fruits[index]);
}

/*Output:-
  apple
  mango
  grapes
  banana
*/

Array Destructuring

Destructuring of array is a method of extracting multiple properties from an array and deconstructing it down into its own constituent parts.

In a simple way, we can take each array element and can assign a variable to each of those using a special syntax called the spread operator which expands the array into its constituent elements.

const myArray = ["value1", "value2", "value3"];

const [var1, var2, var3] = myArray;

console.log(var1);  // value1
console.log(var2);  // value2
console.log(var3);  // value3

var1, var2, and var3 can be used as normal variables.

Now, if we want to put value3 in var2, we have to skip an index by putting , and blank space like this ๐Ÿ‘‡

const [var1, , var2] = myArray;

console.log(var1);  // value1
console.log(var2);  // value3

Now, if we want to put more than one value inside a variable making it another array we can take the help of rest operator which collects multiple elements and condenses them into a single element.

const myArray = ["value1", "value2", "value3", "value4", "value5"];

const [var1, var2, ...newArray] = myArray;

console.log(var1);  // value1
console.log(var2);  // value2
console.log(newArray);  // ["value3", "value4", "value5"]

That's all from my side, if you want to know more, refer Arrays - MDN

Happy coding ๐Ÿ˜„โœจ

ย