How to loop through an array in JavaScript? Example Tutorial

There are several ways of traversing an array in JavaScript. But, before we delve fully into that we need to understand what an array is in JavaScript.

What then is an Array in JavaScript?

An array is a single variable that is used to store different elements. This means that JavaScript array(s) can hold different types of data like the number, string, boolean and object values at the same time.


This is just opposite to arrays in Java where you just can’t do that. It is strongly typed in fact from creation time you would specify what type of data is coming in and its length. And you can’t do otherwise once you have stated the type of data and length any attempts to do that leads to compilation error.

Also, the length of an array is dynamically sized and can keep growing. In other words, you don’t need to specify the array size upfront. You can access the values by referring to an index number. The index number starts from zero as you can see from the image below. The first item in the array is index 0, the second item, index 1. the third item, index 2. E.t.c

Know that JavaScript Array Iteration methods operate on every array item.




Different ways to loop over an array in JavaScript - Examples

We have different ways to create an array in javaScript but the more preferred and common way to create an array is to use the array literal notation, The array literal form uses the square brackets [] to wrap a comma-separated list of elements. The following example creates the colors array that holds three strings:

  1. let colors = ['red', 'green', 'blue'];

You can as well create an empty array for later use by doing the following:

  1. Let my_Array = [];
Under the hood, JavaScript knows the length of the elements in there. And it can always expand joyously unlike java that once you have specified the length at creation, sorry You can’t go beyond that. Hence, you have an array index out of bounds exception.

Fig 1.0, JavaScript array iteration. 


How to create an Array in JavaScript? Examples

Here is how you create an array in JavaScript:

Also, Know that you can always create an array and leave it for later use, it is simply by doing this:

Arrays in JavaScript has the following inbuilt methods to make your task(s) easier:

The join() method also joins all array elements into a string.

The pop() method returns the value that was "popped out"

The push() method adds a new element to an array (at the end)When you work with arrays, it is easy to remove elements and add new elements.

 The shift() method removes the first array element and "shifts" all other elements to a lower index and returns the value that was "shifted out".

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements, and returns the new array length.

The splice() method can be used to add new items to an array, specifying what index you want to add the new items.

The concat() method creates a new array by merging (concatenating) existing arrays, Note that The concat() method does not change the existing arrays. It always returns a new array. The concat() method can take any number of array arguments.



1. Array.forEach() Example in JavaScript 

The forEach() method calls a function (a callback function) once for each array element.

Example:

  1. const numbers = [45,4,9,16]
  2. numbers.forEach(number=> console.log(number));

So, with the above lines of code, the method forEach() loops through each number in the array, and as it does it prints it out one after the other.

Output:

 [45,4,9,16]




2. Array.map() Example in JavaScript

The map() method creates a new array by performing a function on each array element.

The map() method does not execute the function for array elements without values.

The map() method does not change the original array.

 Example

  1. const numbers1 = [45, 4, 9, 16, 25];
  2. const numbers2 = numbers1.map(myFunction);
  3. function myFunction(value, index, array) {
  4. return value * 2;
  5. }
  6. console.log(numbers2)

Note that the function takes 3 arguments:

The item value

The item index

The array itself

When a callback function uses only the value parameter, the index and array parameters can be omitted:

The method in this loops through each item and as it does, it  multiplies each array value by 2 and prints  out the following:

[ 90, 8, 18, 32, 50 ]




3. Array.filter() Example in JavaScript 

The filter() method creates a new array with array elements that pass a test or meet a particular condition that was given.

This example creates a new array from elements with a value larger than 18:

Example

  1. const numbers = [45, 4, 9, 16, 25];
  2. const over18 = numbers.filter(myFunction);
  3. function myFunction(value, index, array) {
  4. return value > 18;
  5. }
  6. console.log(over18)

So, this function returns the following.

OUTPUT:

[45,25]


That's all about different ways to iterate or loop over an array in Java. If you ask me, forEach is my preferred way to loop over an array in JavaScrip but you can also use other methods based upon your requirement.s 

Other JavaScript and Web Development Courses You May like to explore


Thanks for reading this article so far. If you like these best JavaScript design pattern courses, please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

P. S. - If you are new to Javascript and looking for a free JavaScript course, you can also check out this free JavaScript Essentials course from Udemy. It's completely free, and you just need an Udemy account to join this course.


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.