Hi, everyone, in this module, we will be learning Arrays in JavaScript. So far we have learned variables, data types, conditional statements, break and continue statements, and strings in JavaScript. Now, it’s time to know more about arrays.
Arrays in JavaScript
In JavaScript, an array is a user-defined or non-primitive data type used to store a collection of elements in a single variable.
Arrays in other programming languages like C, C++, and Java are used to store the same type of elements, but in JavaScript, an array can be used to store both the same and different types of elements i.e., you can store elements in the form of a number, string, Boolean, a character in a single array.
How to create an array in JavaScript?
In JavaScript, an array can be created in two ways:
- Using Array literal
Syntax
var variable_name=[element1, element2,……., element n];
Examplevar num=[1,4.5,true,'Rahul',null,undefined]; console.log(num); // Output //[1, 4.5, true, "Rahul", null, undefined]
- Using a new keyword
Syntax
var variable_name=new Array(param1,param2,…..);
where arg1, arg2,…. is a parameter list, which is optional.
Examplevar a=new Array(); a[0]=2; a[3]=1; a[1]=4; console.log(a); var b=new Array(2.2,1,'A',"JavaScript"); console.log(b); // Output // [2, 4, empty, 1] // [2.2, 1, "A", "JavaScript"]
The first method is mostly used because it is simple to create and fast execution when compared to creating an array using a new keyword.
If we check the data type of the array, we will get an object as an output.
var num=[1,4.5,true,'Rahul',null,undefined]; console.log(typeof num); //Output //object
Why should we use arrays in JavaScript?
Suppose you want to store 50 names. You can simply store it in a variable if the number of names is less, say 10, but to store 50 names, making 50 variables for each name is a very tedious and tough task. It also increases the complexity of code and program length. So, a solution is to store all the students’ names in a single variable. Thus, an array is required to store or hold multiple values at a time.
How to access array elements in JavaScript?
The elements of the array can be accessed using its index number. The index position of the array starts from 0 and ends at the length of an array-1.
let name=['Sneha','Piyush','Aman','Om']; console.log(name[0]); console.log(name[2]); //Output //Sneha //Aman //If we exceed the index position of the array, we will get undefined as an output. console.log(name[4]); // Output // undefined
Updating an element in an array in JavaScript
var num=[13,26,21,10,6,9]; console.log(num); num[2]=-43; num[0]=3; console.log(num); //Output //[13, 26, 21, 10, 6, 9] // [3, 26, -43, 10, 6, 9]
Deleting an element in an array in JavaScript
var num=[13,26,21,10,6,9]; console.log(num); delete num[2]; console.log(num); //Output //[13, 26, 21, 10, 6, 9] //[13, 26, empty, 10, 6, 9]
Length property in an array in JavaScript
The length property is used to return the length of an array.
Syntax
Array.length
let name=['Sneha','Piyush','Aman','Om']; console.log(name.length); //Output //4
We can use the length property to print the last element of an array.
let len=name.length; console.log(name[len-1]); //Output //Om
Array Methods in JavaScript in JavaScript
- sort()
It is an array method used to sort the elements of the array in ascending or increasing order.
Syntax
array.sort();const a=[4,2,1,3,5]; const b=['JavaScript',"AngularJS","ReactJs","MongoDB"]; console.log(a.sort()); console.log(b.sort()); //Output //[1, 2, 3, 4, 5] //["AngularJS", "JavaScript", "MongoDB", "ReactJs"]
- reverse()
It is a method used to reverse the elements of an array.
Syntax
array.reverse();const a=[4,2,1,3,5]; console.log(a); console.log(a.reverse()); //Output //[4, 2, 1, 3, 5] //[5, 3, 1, 2, 4]
- pop()
It is a method used to remove and return the last element of an array. If the array is empty, undefined is returned as an output.
Syntax
array.pop();const a=[4,2,1,3,5]; console.log(a); let b=a.pop(); console.log(b); //Output //[4, 2, 1, 3, 5] //5
- push()
It is an array method used to insert an element at the end of an array.
Syntax
array.push(element);const a=[4,2,1,3,5]; console.log(a); a.push(0); console.log(a); //Output //[4, 2, 1, 3, 5] //[4, 2, 1, 3, 5, 0]
- shift()
It is used to remove or delete and return the first element from the array.
Syntax
array.shift();const a=[4,2,1,3,5]; console.log(a); let b=a.shift(); console.log(b); console.log(a); //Output //[4, 2, 1, 3, 5] //4 //[2, 1, 3, 5]
- unshift()
It is used to add or insert and return the first element from the array.
Syntax
array.unshift(element);const a=[4,2,1,3,5,0]; console.log(a); a.unshift(6); console.log(a); //Output //[4, 2, 1, 3, 5, 0] //[6, 4, 2, 1, 3, 5, 0]
- concat()
It is a method used to concatenate two or more arrays.
Syntax
array.concat(arr1,arr2,…);var a=[1,4]; let b=["C",'Komal',5]; let c=a.concat([3,6]); console.log(c); let d=a.concat(a,b); console.log(d); //Output //[1, 4, 3, 6] //[1, 4, 1, 4, "C", "Komal", 5]
- join()
It is used to convert multiple values of an array into a single string value.
Syntax
array.join(separator)
The separator is optional.var c=['p','h','p']; let a=c.join(); let b=c.join('/') console.log(a); console.log(typeof(a)); console.log(b); //Output //p,h,p //string //p/h/p
- includes()
This array method is used to return true if the given element is found in an array, otherwise, it returns false.
Syntax
array.includes(element);let a=[3,"Raman",8.9,0]; console.log(a.includes("Raman")); console.log(a.includes(8)); console.log(a.includes(3,1)); //Output //true //false //false
- find()
This array method is used to search and return the first element in an array that satisfies a given condition.
Syntax
array.find(function_name);let num=[19,23,12,8,3,6,4]; let greater=num.find(element => { return element>=15; }); console.log(greater); // Output //19
- filter()
It is used to return a new array based upon a given condition.
Syntax
array.filter(function_name);function check_even(element) { return element%2==0; } let num=[19,23,12,8,3,6,4]; let even=num.filter(check_even); console.log(even); //Output //[12, 8, 6, 4]The above example can be done using arrow function. let num=[19,23,12,8,3,6,4]; let even=num.filter(element => { return element%2==0; }); console.log(even);
- indexOf()
It returns the index of the first occurrence of a given element in an array if found, otherwise, it returns -1.
Syntax
array.indexOf(element,start);The start is the starting index where searching starts and is optional.let num=[19,23,12,8,3,6,4]; console.log(num.indexOf(8)); console.log(num.indexOf(5)); console.log(num.indexOf(6,2)); //Output //3 //-1 //5
- lastIndexOf()
It returns the index of the last occurrence of a given element in an array if found, otherwise, it returns -1.
Syntax
array.lastIndexOf(element,index)
The start is a starting index where searching starts from backward and is optional.let num=[15,2,10,8,3,2,4]; console.log(num.lastIndexOf(2)); console.log(num.lastIndexOf(5)); console.log(num.lastIndexOf(10,4)); //Output //5 //-1 //2
Multi-dimensional array in JavaScript
A multi-dimensional array is an array within another array. We can create a 2-D array, a 3-D array, and so on.
In a 2-D or 2-dimensional array, elements are organized in the form of a matrix. There are several rows and columns in it.
var info=[["Aman",21,"BCA"],["Akash",20,"BA"],["Sneha",21,"Btech"]]; console.log(info);
(index) | 0 | 1 | 2 |
0 | ‘Aman’ | 21 | ‘BCA’ |
1 | ‘Akash’ | 20 | ‘BA’ |
2 | ‘Sneha’ | 21 | ‘BSc’ |
In a 2-D array, we need two indices, one for the row and the other for the column, to access an element.
console.log(info[0][0]); // Output // Aman
info[0][0] means that the element at the 0th row and 0th column is accessed. Similarly, you can access all the other elements of the 2-D array.
var info=[["Aman",21,"BCA"],["Akash",20,"BA"],["Sneha",21,"Btech"]]; for(let i=0;i<info.length;i++) { for(let j=0;j<info[i].length;j++) console.log((j+1),info[i][j]); console.log(); } // Output //1 Aman //2 21 //3 BCA //1 Akash //2 20 //3 BA //1 Sneha //2 21 //3 Btech
I hope this module has helped you a lot in knowing arrays in JavaScript. You might be excited to implement the same by yourself to gain practical knowledge. Stay tuned with us for more modules like this. Keep Coding!