Store Multiple Values in one Variable using JavaScript Arrays:
With JavaScript array variables, we can store several pieces of data in one place.
You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
const sandwich = ["peanut butter", "jelly", "bread"];
You can store numbers in the arrays as well just don't use quotes around them.
Nest one Array within Another Array:
You can also nest arrays within other arrays, like below:
const teams = [["Bulls", 23], ["White Sox", 45]];
This is also called a multi-dimensional array.
Access Array Data with Indexes:
We can access the data inside arrays using indexes.
Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array has an index of 0.
Example
const array = [50, 60, 70];
array[0];
const data = array[1];
array[0] is now 50, and data is 60.
Note: There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
Modify Array Data With Indexes:
Unlike strings, the entries of arrays are mutable and can be changed freely, even if the array was declared with const.
Example:
const ourArray = [50, 40, 30];
ourArray[0] = 15;
Note: There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
No comments:
Post a Comment