JavaScript Arrays

An array is a special variable, which can hold more than one value at a time. JavaScript arrays are written with square brackets. Array items are separated by commas.

Example 1: Write a function in javascript to store subjects in array.

 <html> 
   <head>
     <script> 
      function fun()
      {
        var subjects = ["Maths","English","Computer Science","Hindi","Science"];
        document.getElementById("demo").innerHTML = subjects[2];
      }
    </script>
  </head>
  <body>
    <p id="demo" onclick="fun()">Click to Find Subject</p> 
  </body> 
 </html>

JavaScript Array Methods:

1. Sorting Array - The sort() method is used to sort an array alphabetically.

var subjects = ["Maths","English","Computer Science","Hindi","Science"]; 
subjects.sort();

2. Reverse Array - The reverse() method reverses the elements in an array. You can use it to sort an array in descending order.

var subjects = ["Maths","English","Computer Science","Hindi","Science"]; 
subjects.sort();
subjects.reverse();

3. Numeric Sort - The sort method cannot be used on a number array, because it sorts alphabetically (25 is bigger than 100). You can fix this by providing a function that returns -1, 0, or 1.

var nums = [40, 100, 1, 5, 25, 10];
nums.sort(function(a, b){return a-b});

Numeric Reverse Sort - Use the same trick to sort an arrays in descending order.

var nums = [40, 100, 1, 5, 25, 10];
nums.sort(function(a, b){return b-a});

4. Push: The push() method adds a new element to an array in the end.

subjects.push("Web Designing");

5. Pop: The pop() method removes the last element from an array.

subjects.pop();

6. Shift: The shift() method removes the first element of an array.

subjects.shift();

7. Unshift: The unshift() method adds a new element to an array at the beginning.

subjects.unshift("Web Development");

Example Array

Example 2: Push, Pop JavaScript Array.