Arrays
An Array is an Object which stores multiple elements in it. it can be same type or different types.
Creating Arrays in JavaScript
In JavaScript we can create array in 2 ways
1. Using Array Literal Notation
2. Using Array() Constructor
Creating Arrays using Array Literal Notation
In this method of creating Array we simply use Square brackets and then put all the elements inside this using comma separated.
Ex:-
var arrLit1 = []; //This is Empty Array
var arrLit2 = [1,2,3]; //Array with numbers and length 3
var arrLit3 = ["Foo","Bar"];//Array with Strings and length 2
Creating Arrays using Array() Constructor
In this method We need to explicitly define the Array() with javascript's "new" Keyword
For the Array() Constructor, If we pass don't pass any arguments, then Array will be created with Zero length. If we pass one argument(Number) to the Array(), Array will be created with the passed argument as length. If we specify multiple arguments inside the constructor, then array will be created with those arguments and number of arguments wil be the lenght of the array.
Ex:-
var arr1 = new Array(); //This is Empty Array
var arr2 = new Array(10); //Array with length 10
var arr3 = new Array("foo"); //Here Array with foo element created which is of length 1
var arr4 = new Array(1,4,3); //Array with specified elements and length 3
We can create An array with mixed data types as shown in below example
var arr3 = new Array("ss",1);
Array Length
"length" is the property of Array. It will return the number of elements it currently holding or the length defined using the Array() constructor while creating the array.
Ex:-
var arr = new Array("foo","bar");
console.log(arr.length) ; // It will print 2 in the console.
var arr = new Array(10);
console.log(arr.length) ; // It will print 10 in the console.
How to Access Contents of an array?
To access the contents of an array in JavaScript we need to use the index.
INDEX specifies the position of the element in the Array. The first element has an index of 0.
Ex:-
var arr = new Array("foo","bar");
console.log(arr[0]); //prints "foo"
arr[0] = "newVal"; //0 th index element(1st element) value replaced with "newVal"