Javascript arrays

Javascript arrays

Learn how to create a Javascript array, an object that can hold many values within itself


An array is an object that is used to store multiple variables. These can be useful when storing large amounts of related data, especially when you don't know how many variables there might be.


Basic Javascript array syntax


var names = [ "bob" , "john" , "fred" ]; 

Due to Javascript variables being able to take any data type, there is no need to declare the data type as an array. All that must be done is surround the variables you are inserting with square brackets and separate them with commas. The inserted variables can be off any data type (integers, strings and even objects).


Accessing array elements


var name1 = names[ 0 ]; //bob       
var name2 = names[ 1 ]; //john       
var name3 = names[ 2 ]; //fred

To access array elements, we call the names array followed by the index of the element you wish to select surrounded by square brackets. Array indexes start from 0, meaning that the first name - bob - has an index of 0 and the third name has an index of 2.


Modifying array elements


names[ 0 ] = "rob";

By assigning a new value to a specific element in the array, we can modify the element at that position. Element 0 "bob" has been modified to "rob"


Adding new elements to an existing array


names.append( "michelle" );

The append() method allows us to add an element to the end of an array. This element would have an index of 3 as it is in the fourth position now (remember, the index starts at 0).


Removing array elements


names.splice( 3, 1 );

The splice() method is used to remove elements from an array. The first parameter takes the index of the element you wish to remove (3 in this case is the element containing "michelle" which we added above). The second parameter is for the number of elements you wish to remove, in this case we just remove 1 element.


Other array methods and properties


var names = [ "bob" , "john" , "fred", "michelle" ];       
names.length // returns the length of the array (4)       
names.toString() // returns the array in string format ("bob,john,fred,michelle")       
names.pop() // Removes the last element in the array       
names.sort() // sorts the array (in this case alphabetically)       
var moreNames = [ "rick", "carter" ];       
var newNames = names.concat( moreNames ); // combines 2 or more arrays into a new one       



Christopher Thornton@Instructobit 4 years ago
or