Let's begin without any delay!
When we want to store multiple related values sequentially, we make use of arrays. Instead of creating multiple variables for each value, we can assign all those values to an array.
 i.e. square brackets with multiple values separated by comma(
,). Let's see an example
var myArray = ["butter", "cheese", "milk"]
myArray is now an array. It can contain values of different data types as well.
One can also nest array within other arrays. These are called multi-dimensional arrays. For e.g.
var myArray = [["John", 12], ["Maxwell", 18]]
Here you can see, we have defined multiple arrays within an array. This is what we refer to as nested arrays.
We can access array elements in the same way we deal with string i.e. using indexes.
myArray; // returns the first element of an array
Unlike strings, arrays are mutable i.e. you can change the values that exist within an array. For e.g.
var myArray = [5, 4. 7, 2]; myArray = 3; // now the array looks like [5, 4, 3, 2]
Accessing nested array elements can be achieved by using multiple brackets where first pair of brackets refers to the outermost array and subsequent pairs would access the subsequent nested arrays. Let's clear it with an example from freeCodeCamp itself.
var arr = [ [1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14] ]; arr; // equals [[10,11,12], 13, 14] arr; // equals [10,11,12] arr; // equals 11
push() method to append a value to the end of an array. Let see its usage with a short example
var arr = [1, 2]; arr.push(3); // arr is now [1, 2, 3] arr.push([4, 5]); // arr is now [1, 2, 3, [4, 5]]
pop() method works, just as opposed to
push() i.e. it pops out or removes the last element of an array and returns that element. When I say, return an element, it means we can store the value returned by
pop() in case we want.
Considering the above updated array as an example
arr.pop(); // Returns [4, 5], now array will be [1, 2, 3] arr.pop(); // Returns 3 as it is the last element of updated array
We know that
pop() removes the last element of an array. But what if we want the first element to be removed? Well, we can use
shift() for that. It removes the first element and returns that.
var arr = [1, 2, 3]; arr.shift(); // Returns 1, now array will be [2, 3]
unshift() works just like
push() but instead of adding an element to the end, it adds an element to the starting of array. Let's see an example
var arr = [2, 3]; arr.unshift(1); // arr is now [1, 2, 3]
Side project which became a mind-blowing automated IDE
Przemyslaw Michalak -
Visual Studio Code Extensions, not just the "Must have top 10..."
Tre Tuna -
Afonso Pacifer -
My favorite resources being a freelancer as a side hustle 💎
Leonardo J. 👨🏻💻 -