Array
Array is a variable where we can store more than one value. JavaScript arrays can store any valid value, including strings, numbers, objects, functions, and even other arrays.
Syntax
Example :
Accessing the Elements of an Array
Array elements can be accessed by their index using the square bracket notation. Array indexes are zero-based. This means that the first item of an array is stored at index 0 and goes up to index n-1(where n is number of elements in an array).
Example :
Getting the Length of an Array
The length property returns the length of an array, which is the total number of elements contained in the array.
Example :
Adding New Elements to an Array
To add a new element at the end of an array, use the push() method.
Example :
To add a new element at the beginning of an array, use theunshift() method.
Example :
Removing Elements from an Array
To remove the last element from an array, use the pop() method.
Example :
remove the first element from an array use the shift() method.
Adding or Removing Elements at Any Position
To add or remove elements from any index, use the splice() method. The splice() method returns array of deleted elements.The original array will be modified.
Syntax
The first parameter (startIndex) defines the position where new elements should be added (spliced in).
The second parameter (deleteCount) defines how many elements should be removed.
The rest of the parameters (“elem1” ,…., “elemN”) define the new elements to be added.
Example :
Creating a String from an Array
To create a string by joining the elements of an array, use thetoString() method or join() method. The join() method takes an optional parameter which is a separator string that is added in between each element.
Example :
Extracting a Portion of an Array
To extract a portion of an array, use slice() method. The slice() method returns an new array object selected from start to end. The original array will not be modified.
Syntax
Example :
Merging Two or More Arrays
The concat() method can be used to merge or combine two or more arrays. This method does not change the existing arrays, instead it returns a new array.
Example :