var myArray = ["Logan", "Mike", "Sam"]; var anotherArray = [10, 12, 15, 100, 42]; var oneMoreArray = ["New York", 92, "LA", 25, 46];
You can also nest arrays (put one array inside another array)
var nestedArray = [["Dogs", 4], ["Cats", 7]];
In the above example, one array named
nestedArray is a container for two other arrays
This kind of array is also called a multi-dimensional array.
Data stored inside the arrays can be accessed using indexes. Just like strings, arrays also have zero-based indexing i.e., the first element of the array has an index on zero, the second element has an index of one, the third element has an index of two and so on.
To access the data inside an array all you need to do is, write the name of the array along with the index of data you want to access in square brackets (
You can either output this value or store it in another variable for further use.
var myArray = [10, 45, 87, 56]; console.log(myArray); // output: 10 console.log(myArray); // output: 45 var myData = myArray; // variable holds 87 as value var myData2 = myArray; // variable holds 56 as value
Accessing of data inside multi-dimensional arrays can also be done using indexes, but this time we have to use two sets of square brackets. The first one for the outer-most array (that is the container of all the other arrays) and the second one for the inside array.
var alsoArray = [[90, 45, 65], [34, 72, 46], [100, 81, 94]]; console.log(alsoArray); // output: 65 console.log(alsoArray); // output: 100
var myArray = [10, 26, 30]; myArray = 20; // now myArray becomes [20, 26,30]
There is a
var myArray = [10, 56]; myArray.push(35); // now myArray is [10, 56, 35] myArray.push(9); // now myArray is [10, 56, 35, 9] myArray.push("Zack"); // now myArray is [10, 56, 35, 9, "Zack"]
pop() is invoked or called it pops a value from the end of an array i.e., it removes the last value from the array. But this is not the only thing this function does, when invoked
pop() function also returns the popped off value and you can store it in another variable.
var breakfast = ["apple", "milk", "toast"]; var removedItem = breakfast.pop(); // now array is ["apple", "milk"] console.log(removedItem); // output: toast
pop() function, the
shift() function is used to remove the first value from the array. This function also returns the shifted off value and can be stored in another variable.
var superheros = ["batman", "black panther", "superman"]; var removedHero = superhero.shift(); // now array is ["black panther", "superman"] console.log(removedHero); // output: batman
unshift() function is somewhat like the
push() function, the only difference is that it adds the given value to the front of the array instead of the end of the array.