Net-informations.com

Loop through an array in JavaScript

JavaScript array can hold many values under a single name, and you can access the values by referring to an index number. There are different ways to loop over arrays in JavaScript , but it can be difficult choosing the right one. Below is a brief explanation of many useful JavaScript statements and methods applicable to looping over arrays and objects.

JavaScript Array for loop

JavaScript for loop iterate over each item in an array. JavaScript arrays are zero based, which means the first item is referenced with an index of 0.

Syntax

example

Output:

For loop Works on every environment and you can use break and continue flow control statements.

JavaScript Array forEach

Modern JavaScript has added a forEach method to the native array object. The forEach methods takes the callback function as an argument and runs on each object present in the array.

Output:

You cannot use break and continue in JavaScript forEach.

JavaScript for-of statement

The for-of statement statement works for any kind of iterable object and also for generators (any object that has a \[Symbol.iterator\] property).

Output:

JavaScript for-of statement can iterate over a large variety of objects and really useful to iterate serially asynchronous values.

Fastest way to loop through an array in JavaScript


Loop through an array in JavaScript

The absolute fastest way to loop through a javascript array is: while(){} .

Why is using "for...in" for array iteration a bad idea?

There are many reason that you should not use "for...in" .

  1. Inherited properties are also enumerated

JavaScript for...in statement will go up in the prototype chain, also enumerating over inherited properties, a thing that sometimes is not desired.

Output:

From the above example you can understand that it can be particularly a problem if you use some library that relies heavily on native prototypes augmentation.

  1. It's construct

Output:

From the above output, you can see the for..in loop shows only the explicitly set index of "5", and ignores 0-4.

In normal JavaScript for loop , iterate over numeric indexes from 0 to 5, as everyone expects.

Output:

  1. It's slow

It's slow because you have to walk all properties of the array object and its whole prototype chain and will still only get the property's name, ie to get the value, an additional lookup will be required










net-informations.com (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About