JavaScript Array

JavaScript Array

Published by: Anil K. Panta

JavaScript Array

Array are container-like values that can hold other values. The values inside an array are called elements.


Example

var breakfast = ["coffee", "croissant"];

breakfast;


Output

["coffee", "croissant"]

Array elements don’t all have to be the same type of value. Elements can be any kind of JavaScript value — even other arrays.


Example

var hodgepodge = [100, "paint", [200, "brush"], false];

hodgepodge;


Output

[100, "paint", [200, "brush"], false]


Accessing Array

To access one of the elements inside an array, you’ll need to use the brackets and a number like this: myArray[3]. JavaScript arrays begin at 0, so the first element will always be inside [0].


Example

var sisters = ["Tia", "Tamera"];

sisters[0];


Output

“Tia”

To get the last element, you can use brackets and `1` less than the array’s length property.


Example

var actors = ["Felicia", "Nathan", "Neil"];

actors[actors.length - 1];


Output

“Neil”

This also works for setting an element’s value.


Example

var colors = ["red", "yelo", "blue"];

colors[1] = "yellow";

colors;


Output

["red", "yellow", "blue"]

We will get back to you via email or phone call