Which is faster? for, for..of and forEach methods in JavaScript | JavaScript Interview Guide

Published: 27 June 2020
on channel: Code Pro
6,534
99

for, for..of and forEach
There are different ways to loop over arrays in JavaScript, but it can be difficult choosing the right one.There is a classic JavaScript for loop, JavaScript forEach method and the for-of loop, introduced in the sixth edition of EcmaScript (ES6), allows the programmer to loop over the actual iterable objects. In this video You will learn different ways to loop or iterate JavaScript arrays.

for loop

The most basic type of iteration method in JavaScript is the for loop. It takes three expressions; a variable declaration, an expression to be evaluated before each iteration, and an expression to be evaluated at the end of each iteration.  Javascript for loop is fastest, but ugly on the eyes.

for...of loops are  the fastest when it comes to small data sets, but they scale poorly for large data sets. slowest, but its a syntactic sugar over for loops.

The execution time of .forEach() is dramatically affected by what happens inside each iteration. fast and designed for functional code

The results were quite interesting and not what I was expecting.  The execution of javascript really depends on
various factors like type of operating system like windows and the type of browser like chrome, IE,Firefox

The traditional for loop is the fastest, so you should always use that right? Not so fast - performance is not the only thing that matters. It is rare that you will ever need to loop over 1 million items in a frontend JS app. Code Readability is usually more important, so default to the style that fits your application. If you prefer to write functional code, then forEach is ideal, while for-of is great otherwise. Fewer lines of code means shorter development times and less maintenance overhead - optimize for developer-happiness first, then performance later.


Watch video Which is faster? for, for..of and forEach methods in JavaScript | JavaScript Interview Guide online without registration, duration hours minute second in high quality. This video was added by user Code Pro 27 June 2020, don't forget to share it with your friends and acquaintances, it has been viewed on our site 6,534 once and liked it 99 people.