Definition
An array is a javascript object which is defined as a collection of elements of any type or simply a collection of data items stored under a single name. Array follows index-based access. The index is nothing but the position of the elements of an array. The index always starts with 0. The array comes under the category of composite or complex data types.
The total number of elements in an array gives the length of the array. In the above example, the length of myArray is 6. but this length is not fixed. We can change the length of an array anytime.
How to Create an Array
- The most basic way to create an array is to simply assign the array values to a variable
const countries= [ 'India' , 'Japan' ,'China','Americal' ];
- Using Array.of() method: This method creates an array that
has the argument as the value of its elements irrespective of
the data type of that argument. Now you might think what's
the difference between the Array constructor and the
Array.of() method? The main difference between them is how
they handle the integer arguments. Let us understand this by
an example
So, the Array.of() method considers the argument as its element and not its length so it will make an array of length 1 with a value of 4 (argument), whereas if we pass 4 as an argument to the Array constructor then it will make an array of length 4 and all the 4 elements will be undefined.Array.of(5); Array(4);
Array.of(2, 4, 6, 8); // [2, 4, 6, 8]
Array(2, 4, 6, 8); // [2, 4, 6, 8]
Let’s confirm this using the length property of the array
console.log(Array.of(5).length); //1
console.log(Array(5).length); //5
So, this proves that the Array.of() method creates an array of 1 element while the Array constructor creates an array of 5 elements.
- Using Array.from() method: This is a static method used to create an array from any object with a length property or any iterable object.
Array.of('Simran', true, {name: 'jagadish', rating: 4.9}, 156) // ['Simran', true, {name: 'jagadish', rating: 4.9}, 156]
console.log(Array.from('jagadish')); // ['j', 'a', 'g', 'a', 'd', 'i' ,'s' ,'h']
How to Acess the Element of an Array
We can access the elements of an array using its index.
const countries= [ 'India' , 'Japan' ,'China','Americal' ];
countries[0]; //India
countries[1]; //Japan
countries[2]; //China
countries[3]; //America
If we want to access the elements of an array from backward, we can simply use the length property.
const countrieslist= [ 'India' , 'Japan' ,'China','Americal' ];
const myLength =countrieslist
countrieslist[-1]; //America
countrieslist[-2]; //China
countries[-3]; //Japan
If we want to access all the elements of an array one by one then we can simply use a loop to save our time.
How to Check if the Given Value is an Array:
To check whether the given value is an array or not we use Array.isArray(value) method. This method returns true if the given value is an array.
Array.isArray('jagadish'); // false
Array.isArray(['jagadish', 146, 52]); // true
Array.isArray(undefined); // false
Array.isArray({totalMarks: 93}); // false
Adding an Element in an Array
The push() method is used to add an element at the end of an array and returns the new length of the array.
const groceryList= [ 'egg', 'butter', 'bread'];
var newLength=groceryList.push('cereals');
console.log(newLength); //4
console.log(groceryList); //[ 'egg', 'butter', 'bread', 'cereals']
You can also push more than one item at the same time.
groceryList.push('rice', 'juice', 'oil');
The push() method adds an element at the end of the array, but what if you want to add an element at the starting of the array? So here comes the unshift() method. The unshift() method is used to add an element at the starting of the array and returns the new length of the array. Like the push() method you can also add multiple values in the array using the unshift() method.
const groceryList= [ 'egg', 'butter', 'bread'];
var newLength=groceryList.push('cereals', 'rice');
console.log(newLength); //5
console.log(groceryList); //[ 'cereals', 'rice','egg', 'butter',
'bread']
Deleting Elements from an Array
The pop() method is used to delete the last element of an array and returns the deleted element.
const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
groceryList.pop(); // rice
console.log(groceryList); // [ 'egg', 'butter', 'bread', 'cereals']
The shift() method is used to delete the first element of an array and returns the deleted element.
const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
groceryList.shift(); // egg
console.log(groceryList); // [ 'butter', 'bread', 'cereals', 'rice']
Determining the Length of an Array
The length method is used to determine the length of an array.
const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
console.log(groceryList.length); //5
Some Important Methods of Array in JavaScript
- slice(): This method is used to extract a specific portion of an array. It returns a new array and does not change the original array. Here start & end denotes the index of elements of the array.
Syntax:
Examples:slice() slice(start) slice(start, end) // end is not included
const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ]; console.log(groceryList.slice(2)); // ['bread', 'cereals', 'rice'] console.log(groceryList.slice(2, 4)); // [ 'bread', 'cereals'] console.log(groceryList.slice(1, 5)); // ['butter', 'bread', 'cereals', 'rice'] console.log(groceryList.slice(-2)); // ['cereals', 'rice'] console.log(groceryList.slice(2, -1)); // ['bread', 'cereals'] //extracting the third element through the second-to-last element in the sequence.
- concat(): This method is used to merge two or more arrays. This method does not change the original arrays but returns the new merged array. Example:
const arrOne = [5, 10, 15];
const arrTwo = [20, 25, 30];
const arrThree=[35, 40, 45]
const arrFour = arrOne.concat(arrTwo);
const arrFive = arrOne.concat(arrTwo, arrThree)
console.log(arrFour); // [5, 10, 15, 20, 25, 30]
console.log(arrFive); // [5, 10, 15, 20, 25, 30, 35, 40, 45]
- join(): This method joins all the elements of an array and returns a new string separated by a separator. By default, the separator is a comma (,) but we can it by passing an argument to the join() Example
const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ];
console.log(groceryList.join()); // "Egg,Butter,Bread,Cereals"
console.log(groceryList.join('')); // "EggButterBreadCereals"
console.log(groceryList.join('-')); //"Egg-Butter-Bread-Cereals"
- fill(): This method fills all the array (or only the specified) elements with a static value. This method modifies the original array.
Example:
const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ]; groceryList.fill('Rice'); console.log(groceryList); // [ 'Rice', 'Rice', 'Rice', 'Rice' ]
- includes(): This method is used to check whether an
element is present in an array or not. If the element is
present
then it will return true else it returns false.
Example:
const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ]; groceryList.includes('Rice') //false groceryList.includes('Bread') //true
- indexOf(): This method is used to find the index of an element in an array. If an element is not present then indexOf() method returns -1
Example:
If an element is present more than one time then the indexOf() method returns the index of its first occurrence. If we want to know the last occurrence of that element then use lastIndexOf().const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals', 'Bread' ]; groceryList.indexOf('Butter'); // returns 1 groceryList.indexOf('Rice'); // returns -1 groceryList.indexOf('Bread'); // returns 2
const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals', 'Bread' ]; groceryList.lastIndexOf('Bread'); // returns 4
- reverse(): This method reverses the position of all the elements in an array. This method modifies the original array. Example:
8.sort(): This method first converts all the elements of the array into a string and then sorts them in ascending order. This method modifies the original array. Example:const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ]; groceryList.reverse(); // returns [ 'Cereals', 'Bread', 'Butter', 'Egg']
9.at(): As we have seen above, to access the elements of an array backward we use the length of an array. at() method allows us to directly traverse the array backward without using the length method by directly using negative value. Example:const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ]; groceryList.sort(); //returns [ 'Bread', 'Butter', 'Cereals', 'Egg', 'Rice' ]
const groceryList= [ 'Egg', 'Butter', 'Bread' ]; groceryList.at(0); // Egg groceryList.at(1); // Butter groceryList.at(2); // Bread groceryList.at(-1); // Bread groceryList.at(-2); // Butter groceryList.at(-3); // Egg
Summary
-- An array is a collection of data items (same or different) stored under a single name. -- Array follows index-based access. The index always starts with 0. --For insertion of element we use push() & unshift() method whereas for deletion we use pop() & shift() method. --Some methods to create an array is using Array constructor, Array.of(), Array.from(), and the spread operator( ... --Array.isArray(value) is used to determine if the passed value is an array or not.