Introduction to the JavaScript Arrays

Introduction to the JavaScript Arrays

This is a brief article about the Arrays in JavaScript in which I had discussed about the important methods and use of arrays.

JavaScript Array

Array is a special type of variable in JavaScript which can store multiple values or more than one value in it, these values can be of any types.

For eg:- We want to store name of 3 subject then we will need 3 variable to do so like-

let subject1 = "Maths";
let subject2 = "Computer";
let subject3 = "Science";

But if we will use the array to do the same task then we can store all these three values in a single variable as shown below-

let mySubject = ["Maths", "Computer", "Science"];

Note: By above given example we can see that arrays are very helpful while storing multiple value in it.

Syntax for Array Declaration and Initialization

const array_name[];
array_name[0] = item1;
array_name[1] = item2;
array_name[2] = item3;

or

const array_name = [item1, item2, item3, ...];

Syntax Explanation

  1. const:- We can use let, var or const to declare an array but const is recommended to use while declaration.

  2. array_name:- We have to choose an array name for our array which can be anything meeting the conditions for naming a variable.

  3. We can initialize the items after the declaration of array by it's index value which always starts from zero as shown in the first approach either we can choose the second one where we had declaration and initialization both at the same place.

Note:- We can have multiple elements in our arrays having different data types together.

As we have seen in other popular programming languages like C++ and Java that the array can only store multiple values of similar type in it, which is not true in the case of the JavaScript. We can hold multiple values of different type in it as shown below in the example-

const myArray = ["Hashnode", true, 45, NULL, 10.5];

or

const myArray[];
myArray[0] = "Hashnode";
myArray[1] = true;
myArray[2] = 45;
myArray[3] = NULL;
myArray[4] = 10.5;

Creating an Array using the New Keyword

We can also used the JavaScript new keyword to create an array which is demonstrated through the given example below-

const subjects = new Array("Maths", "Computer", "Science");

We can use any of the two methods to create an array, both will work fine for us.

Accessing an Array Element

We can access an array element by using the Index Value of that particular element.

Array Index always starts from the Zero similar to that of any programming language.

const subjects = ["Maths", "Computer", "Science"];
// There are three elements in the array having index value 0, 1, 2 in it.
let item1 = subjects[0] // This will store Maths in it.
let item2 = subjects[1] // This will store Computer in it.
let item3 = subjects[2] // This will store Science in it.

We can also access the whole array by using it's name as shown in the below example-

const subjects = ["Maths", "Computer", "Science"];
console.log(subjects); // Just to see the result in the console
// Preferred to use document.write to print it in the document.

Modifying the Array Element data

As we have accessed the data from the array, in the similar manner we can also change the data of an element using it's index value.

const subjects = ["Maths", "Computer", "Science"];
subjects[0] = "Drawing"; // Maths will be replaced with the Drawing.

Some important Array Methods to use

Array Length

We can use length property of an array to find the length of that array, which is quite useful when we wants to print all the elements of an array using the basic for loop.

const subjects = ["Maths", "Computer", "Science"];
let arrayLength = subjects.length;

Printing an array using basic for loop and length function

const subjects = ["Maths", "Computer", "Science"];
for(let i=0; i<subjects.length; i++){
      console.log(subjects[i]); // Output will be shown on console
}

Array Push and Pop

In array push is used to insert an element at the end of the array while the pop is used to delete an element from the end of the array.

const subjects = ["Maths", "Computer", "Science"];
subjects.push("Drawing");
console.log(subjects);
// Output
// ["Maths", "Computer", "Science", "Drawing"]

subjects.push("Social Science");
console.log(subjects);
// Output
// ["Maths", "Computer", "Science", "Drawing", "Social Science"]

subjects.pop();
console.log(subjects);
// Output
// ["Maths", "Computer", "Science", "Drawing"]

subjects.pop();
subjects.pop();
subjects.pop();
console.log(subjects);
// Output
// ["Maths"]

Array Shift and Unshift

The array shift method is used to delete an element from the beginning of array and shifts all the elements to the left by one position so that the space of deleted elements can be filled by the remaining ones.

const subjects = ["Maths", "Computer", "Science"];
subjects.shift();
console.log(subjects);
// Output
// ["Computer", "Science"]

The array unshift method is used to insert an element in the beginning of the array and move all the other element to the right by one position.

const subjects = ["Maths", "Computer", "Science"];
subjects.unshift("Drawing");
console.log(subjects);
// Output
// ["Drawing", "Maths", "Computer", "Science"]

Note:- shift deletes from the beginning and pop deletes from the end while unshift insert at beginning and push inserts at last.

Array toString Method

This method is used to create a single string of comma seperated values from a given array. The whole array will be converted in a string in which the elements will be separated with the commas.

const subjects = ["Maths", "Computer", "Science"];
let mySubjects = subjects.toString();
console.log(mySubjects)
// Output
// Maths,Computer,Science

Array join Method

Join method is quite similar to that of the toString method, it also joins the element of an array together to create a string but in addition we can also specify that how the elements should be separated after joining. In toString values or elements were separated by commas by default to which we can change in join.

const subjects = ["Maths", "Computer", "Science"];
let mySubjects = subjects.join(" joined ");
console.log(mySubjects)
// Output
// Maths joined Computer joined Science

Array concat Method

This concat() method is used to merge two or more arrays together which does not modify the original array but creates a new array which has all the merged elements in it.

const greenVeg = ["Spinach", "Tomato", "Carrot"];
const fruits = ["Banana", "Apple", "Mango"];
const healthyFood = greenVeg.concat(fruits);
// Output
// Spinach,Tomato,Carrot,Banana,Apple,Mango

Splice in Array

The splice() method is used to add new elements to an array, splice method can also be used to remove a particular element.
The below example will demonstrate that how a new element can be added into an array using the splice method-

const mySubject = ["Maths", "Computer", "Science"];
mySubject.splice(2, 0, "Social Science");
// The first parameter (2) is denoting the position at which we want to insert the element.
// The second parameter (0) is denoting that we do not want to delete any element from it.
// The third parameter (Social Science) is the element to which we want to add
// We can add as many element as want by separating them by comma.

//Output
//["Maths", "Computer", "Social Science", "Science"]

Code for deleting an element using the splice method We can simply pass the first and second argument in the splice method to delete an element, the first argument will become zero as we do not want to add any element and the second argument will have the number of elements we want to delete as we can see in the code below-

const mySubject = ["Maths", "Computer", "Science"];
mySubject.splice(0, 2);
// Output
// ["Science"]

Slice in an Array

Slice method is used to get a particular portion of an array, we can also say that by using this method we can get a particular part of an array according to our will.

const subjects = ["Maths", "Computer", "Science"];
let values = subjects.slice(2);
// If we will pass only one argument then it will give us an array from the passed index to the end 

let newValue = subjects.slice(0,2);
// This will give us the element at index 0 and 1 because the first argument is inclusive and the second argument is exculsive.

Sorting an Array

For sorting an array in JavaScript, we uses sort method. Sort method can be used on string, number or any of the array to sort it.

const myArray = [10, 25, 32, 8, 5, 40];
myArray.sort();

Reversing an Array

Like sorting, we can also reverse an array by using the reverse method. This method will reverse the whole array.

const myArray = [10, 20, 30, 40, 50];
myArray.reverse();