We’ve already learned that JavaScript variables are containers for data values. In JavaScript, both arrays and objects can be used to store multiple values and more complicated information in a single variable.
Arrays
Arrays provide a way to store multiple pieces of information. An array is a list of values: numbers, strings, boolean values, or even other arrays.
1. Store Multiple Values in an Array
Creat an array:
You can create an array by assigning it to a variable, so you start by declaring a variable using the name you want to use to reference the array. Next, you add an equals sign, followed by a pair of square brackets and a semicolon const planets =[];.
The brackets represent an array. Inside the brackets you add a comma-separated list of values. Here we put three strings in this array:
const planets = [
'Mercury',
'Earth',
'Mars',
];
Access Elements in an Array:
To access a single element within an array, use the index, which is a number that indicates the position of an element in an array. So you type the variable name, followed by a pair of brackets with the index in it:
planets[0] //'Mercury'
planets[1] //'Earth'
planets[2] //'Mars'
One important concept about arrays or any other list forms in JavaScript is that the index start from zero. There are 3 elements in this array above: the index of the first element in an array is 0, the second element’s index is 1, the last element’s index in this array is 2, and the length of this array is 3. The .length property returns the number of elements in an array:
planets.length // 3
In JavaScript, an array is not only a type of data structure, an array is also considered a special kind of object that has properties and methods you can use on it.
Add Elements to an Array:
Here are some methods you can use to add new elements to an array:
Use .push() method to add elements to the end of the array:
Arrays
1. Store Multiple Values in an Array
const planets = [
'Mercury',
'Earth',
'Mars',
];
planets[0] //'Mercury'
planets[1] //'Earth'
planets[2] //'Mars'
planets.length // 3
const planets = ['Mercury','Earth','Mars'];
planets.push('Venus');
console.log(planets); // ['Mercury', 'Earth', 'Mars', 'Venus']
const planets = ['Mercury','Earth','Mars'];
planets.unshift('Venus', 'Jupiter'); // To add multiple elements
console.log(planets); // ['Venus', 'Jupiter', 'Mercury', 'Earth', 'Mars']
const planets = ['Mercury','Earth','Mars','Venus'];
planets.pop(); // returns 'Venus'
console.log(planets); // ['Mercury','Earth','Mars']
planets.shift(); // returns 'Mercury'
console.log(planets); // ['Earth','Mars']