How to work with Arrays in Javascript with examples

JavaScript arrays are used to store multiple values in a single variable. JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects. Items in an Array can be accessed using the index of an array. Arrays in JavaScript can be used for various operations and we can perform certain actions in array like adding new item, remove  item, iterate the array , get the index of item etc.

Syntax of an Arrays in JavaScript?

How do I Declare an Array in JavaScript?

Creating an array and assigning values to it is very simple in Javascript. Let’s check out how to create an array in JS in the below example.

How to Access an Array Element in JavaScript?

Array elements can be accessed using the index of an array. Let’ say if we need to access the “iPhone” in above example then we could use console.log(mobiles[0]);.

How to loop through an Array in JavaScript

Arrays in JavaScript can be iterated. We could traverse each element of an array using for loop. Let’s say if you would like to print all the values in an array then simply you could iterate and print the elements.

“foreach” vs “for of” vs “for in” in JavaScript

We have seen how to loop through array using for statement in above example. Now let’s take a look at how to loop through array using “foreach”, “for of” and “for in”

foreach : forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

callback is invoked with three arguments:

  • the element value
  • the element index
  • the array being traversed

Example of JavaScript array using “foreach” loop

for in : The for in statement iterates only over the enumerable properties of an object, in arbitrary order.for in is used to loop through properties of an object.

Note:for…in should not be used to iterate over an Array where the index order is important.

Example of JavaScript array using “for in” loop
The following function takes as its argument an object. It then iterates over all the object’s enumerable properties and returns a string of the property names and their values.

for of: The for…of statement creates a loop Iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

Example of JavaScript array using “for of” loop

Adding item into an Array in JavaScript

Adding item into an Array at front in JavaScript

Remove Last item from an Array in JavaScript

Remove First item from an Array in JavaScript

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.