JavaScript Tutorial

Define JavaScript

JS Arithmetic Exercise

JavaScript Comment

JavaScript Variable

JavaScript Operators

Conditional Statements

Logical Operators

JavaScript Slider

JS Login Form

JS Popup Boxes

JavaScript Loops

JavaScript Arrays

JS Mouse Events

JS Keyboard Events

Styling Elements

External JavaScript

JS Noscript Tag

JS String Functions

JS Math Functions

JS Date Functions

JS Theme Changer

JS Assignment

Page Stats

Visitor: 80

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.

1. <html> 
2.   <head>
3.     <script> 
4.      function fun()
5.      {
6.        var subjects = ["Maths","English","Computer Science","Hindi","Science"];
7.        document.getElementById("demo").innerHTML = subjects[2];
8.      }
9.    </script>
10.  </head>
11.  <body>
12.    <p id="demo" onclick="fun()">Click to Find Subject</p> 
13.  </body> 
14. </html>

JavaScript Array Methods are:

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

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.
Syntax:

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.
Syntax:

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");
Updated: 16-Feb-19