An array in JavaScript is an ordered list of values, and each value is called an element. Arrays are capable of holding values of different data types. They are dynamically sized, meaning you don’t necessarily need to specify the array size upfront because they can automatically increase or decrease in size depending on the operations that are being carried out with them.
To declare an array, we make use of square brackets. Let us take an example by declaring an array of fruits.
Var fruits = [“apple”, “orange”, “avocado”, “mango”];
The elements of the above array can be accessed making use of their index numbers. For example, to access the first element, we type the following line of code.
Fruits[0]
Meaning, the first element of any array (apple) has an index of 0, then the next has an index of 1 and so on. Let’s have a view of the output of the code.
Now let’s take a look at some of the major things we can do with arrays. There are so many things you can do to/with an array. You can remove elements from an array, add elements to an array, replace an element, change the array size, and so on. All of these are possible with the use of array methods.
Array methods are built-in JavaScript functions that being used on arrays. Each method has a unique function which could be a change or calculation. It also saves us from writing our own functions from scratch.
Below are some most commonly used array methods. There are tons of other array methods that are being made use of in JS.
fruits.pop(); //Removes the last element from the array
fruits.sort; // Sorts the elements in the arrayfruits.push(); //Adds new element at the end of the array
Let is try out the first object method above. Writing it gives the following output:
Looking at the fruits array after writing the line of code with the “pop()” array method, you see that the last element which is “mango” has been removed from the array.One other important method is the “concat()” which joins 2 or more arrays together. Let’s declare another array and join its elements to our previous array.
Declaring the new array:
var fruits1 = [“Banana”, “Avocado”, “Grape”];
Now let us join the two arrays together :
var fruits = [“apple”, “orange”, “avocado”, “mango”];
var fruits1 = [“Banana”, “Avocado”, “Grape”];var fruits_new = fruits.concat(fruits1);
The code gives the following output when we view the new array.
You see how exciting JavaScript can be right? We are here to help you master the language so that you can be able to do amazing stuff with it. Stay tuned for more upcoming lessons. Happy coding.
Comments
Post a Comment
Please do not enter any spam link in the comment box.