JavaScript Array and it’s methods

JavaScript arrays are used to store multiple values in a single variable. These values can be of any data type, including numbers, strings, and objects.

One way to create an array in JavaScript is by using the Array constructor. For example:

var fruits = new Array("apple", "banana", "orange");

Alternatively, you can use square brackets to create an array:

var fruits = ["apple", "banana", "orange"];

There are many built-in methods that can be used to manipulate arrays. Some common methods include:

  • push(): adds one or more elements to the end of an array

      fruits.push("pear", "kiwi"); 
      // fruits is now ["apple", "banana", "orange", "pear", "kiwi"]
    
  • pop(): removes the last element of an array

      fruits.pop(); 
      // fruits is now ["apple", "banana", "orange"]
    
  • shift(): removes the first element of an array

      fruits.shift(); 
      // fruits is now ["banana", "orange"]
    
  • unshift(): adds one or more elements to the beginning of an array

      fruits.unshift("strawberry", "blueberry"); 
      // fruits is now ["strawberry", "blueberry", "banana", "orange"]
    
  • sort(): sorts the elements of an array in ascending order

      fruits.sort(); 
      // fruits is now ["banana", "blueberry", "orange", "strawberry"]
    
  • reverse(): reverses the order of the elements in an array

      fruits.reverse(); 
      // fruits is now ["strawberry", "orange", "blueberry", "banana"]
    
  • splice(): adds or removes elements from an array

      fruits.splice(1, 2, "mango", "grapes"); 
      // fruits is now ["strawberry", "mango", "grapes", "banana"]
    

    These are just a few examples of the many methods that can be used to manipulate arrays in JavaScript. It is a powerful tool for handling data in web development and other applications.

    Note: JavaScript Array are 0-indexed, which means the first element of the array is at index 0, the second element is at index 1, and so on.