Arrays In Javascript

JavaScript:-

JavaScript(JS) is a lightweight, high-level just-in-time (JIT) compiled dynamically typed programing language that conforms to the ECMAScript specification.

JS is used to build desktop apps and develop mobile apps for both android and ios and it is also used to build server-side applications.

What is Array in JavaScript?

In JavaScript array is a powerful and comprehensive tool. The array is a single variable that stores multiple elements. The arrays are not a data type of JavaScript, they are just regular objects.

Declaration of Array:-

There are only two ways of declaring an array-

const arr = ["a", "b", "c", "d"] //Method-1
const arr = new Array() //Method-2

Methods of Array-

  • forEach( ) - It is provided a function once for each element of the array.

  • includes( ) - It determines whether an array includes a certain element.

  • indexOf( ) - It returns the first index at which a given element may be found, or -1 if it does not exist.

  • join( ) - Joins all elements of an array into a string.

  • push( ) - This is used to push one or more values into the array.

  • slice( ) - It returns a new array containing a portion of the array on which it is implemented. And the original array remains unchanged.

  • splice( ) - It modifies the contents of an array by removing the existing elements and/or by adding new elements.

  • toString( ) - Converts an array to a string, and returns the result.

      const arr = ['a', 'b', 'c', 'd', 'e', 'f'];
    
      arr.forEach( e => console.log(e)); 
      // expected output : a b c d e f
      console.log(arr.includes('e'));
      // expected output : true
      console.log(arr.indexOf('d'));
      // expected output : 3
      console.log('Sudhanus'.indexOf('d'));
      // expected output : 2
      console.log(arr.join());
      // expected output : a,b,c,d,e,f
      const arr1 = arr.push('g');
      console.log(arr1);
      // expected output : 7
      console.log(arr);
      // expected output : [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]
      console.log(arr.slice(2));
      // expected output : [ 'c', 'd', 'e', 'f', 'g' ]
      console.log(arr.slice(2, 5));
      // expected output : [ 'c', 'd', 'e' ]
      console.log(arr.slice(2, -1));
      // expected output : [ 'c', 'd', 'e', 'f' ]
      console.log(arr.toString());
      // expected output : a,b,c,d,e,f,g