Array 101 in JavaScript

What is an Array?

An Array is an object that can store multiple values at once. All these elements need to be of the same data type, such as an integer or string, or boolean.

How to create an Array?

Syntax:

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

Example:

const mobiles= ["samsung", "nokia", "realme", "Iphone"];

Important Methods of Array in JavaScript

- slice() :

The slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.

Syntax:

slice(start, end)

// start defines the starting index from where the 
// portion is to be extracted.
// end defines the index up to which portion is to be extracted.

Example:

const list= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
console.log(list.slice(2));  //[ 'bread', 'cereals', 'rice' ]
console.log(list.slice(1, 5));  // ['butter', 'bread', 'cereals', 'rice']

- join() :

The join() method returns an array as a string. The default value of the separator is a comma(,).

Syntax:

arrayName.join();

Example:

const list= [ 'Paneer', 'Butter', 'Bread', 'Corn' ];
console.log(list.join());        
// Paneer,Butter,Bread,Corn
console.log(list.join('-'));
// Paneer-Butter-Bread-Corn

- concat() :

The concat() method concatenates (joins) two or more arrays and returns a new array, containing the joined arrays. This method does not change the existing arrays.

Example:

const first = [ 1, 2, 3, 4];
const second = [ 5, 6, 7, 8];
const third = first.concat(second);

- 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 list= [ 'Paneer', 'Butter', 'Bread', 'Corn' ];
list.includes('pakode');  //False
list.includes('Paneer');  //True

- indexOf() :

The indexOf() method is used to find the index of the first occurrence of the search element provided as the argument to the method. This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.

Example:

const list= [ 'Paneer', 'Butter', 'Bread', 'Corn' ];
list.indexOf('Bread');   // 2
list.indexOf('Pakode'); // -1

- reverse() :

The reverse() method reverses the order of the elements in an array. This method overwrites the original array.

Example:

const array = [ 1, 2, 3, 4, 5, 6, 7, 8];
array.reverse();   // 8, 7, 6, 5, 4, 3, 2, 1

- sort() :

The sort() sorts the elements of an array and overwrites the original array. This method sorts the elements as strings in alphabetical and ascending order.

const array = [2, 3, 4, 2, 7, 8, 9, 0];
array.sort();  // 0, 2, 2, 3, 4, 7, 8, 9

More about array methods

  • For insertion of element we use push() & unshift() method.
  • For deletion we use pop() & shift() method.
  • Read more

Thank you for reading. That's All......