JavaScript Arrays

Introduction to Arrays

  • Array is a grouping of objects.
  • It stores multiple values in a single variable.
  • It stores a fixed-size sequential collection of elements of the same type.
  • It is used to store collection of data.

Creating and Initializing Arrays

var variable_name = new Array();     // Creating an Array
var arr = [];                    // Creating an Array
var arr1 = [1, 2, 3];               // Initializing an Array

Multidimensional Array

var arr2 = [
                    [1, 2, 3] ,
                    ['a', 'b', 'c'] ,
                    ['x', 'y', 'z']

Iteration through Arrays

function show_array(arr)
     for (var i = 0; i < arr.length; i++ )
var arr1 = [1, 2, 3];

Array Properties

Array PropertiesDescription
ConstructorIt returns a reference to the array function that created the object.
IndexIt represents the zero-based index of the match in the string.
LengthIt reflects the number of elements in an array.
InputIt presents only an array created by regular expression matches.
PrototypeIt allows you to add properties and methods to an object.

Array Methods

concat()It returns a new array comprised of this array joined with other arrays and values.
every()It returns true if every element in this array satisfies the provided testing function.
filter()It creates a new array with all the elements of this array for which the provided filtering function returns true.
indexOf()It returns the first index of an element within the array equal to the specified value.
join()It joins all elements of an array into a string.
pop()It removes the last element from an array and returns that element.
push()It adds one or more elements to the end of an array and returns the new length of the array.
reverse()It reverses the order of the elements of an array.
sort()It represents the source code of an object.

Example: Program on Array Methods – POP() & PUSH()

          <button onclick="arrpop();">POP</button>
          <button onclick="arrpush();"> PUSH </button>
               function arrpop()
                    var numbers = ["1", "2", "3", "4", "5", "ABC"];
                    document.write(numbers.pop()+" "+"Removed"+"<br>");
                    //pop() removes the last element of an array

                    // Now we have [1,2,3,4,5]
                    document.write("Now length is: "+numbers.length); // ABC removed
               function arrpush()
                    var numbers = ["1","2","3","4","5","6"]
                    // now we got ["1","2","3","4","5","6"]
                    document.write("Added element is :"+" "+numbers[numbers.length-1])
                    // Now we have [1,2,3,4,5,6]
                    document.write("<br>"+"Now length is: "+numbers.length); // 7 Added


array methods push pop