+ 1
Between while loop and for loop which one is more faster In JavaScript
while vs for loop
2 Answers
+ 17
You can always useĀ eitherĀ of the loops. But, the most common usage ofĀ forloops is when theĀ number of iterations are known, and theĀ whileĀ loop havingĀ uncertain number of iterationsĀ or would depend upon a particular condition. Both are good at their own practical works. For Eg.,
var arr = ["a", "b", "c"];
for (let i=0; i<arr.length; i++) { // will loop 3 times (length of arr = 3) // do something }
var x = "Hello";
while (x != "World") { // do something if (some_condition) { // do something } else x = "World"; }
+ 3
Seems "for" loop is faster.
You can check by using
console.time(); //start time
console.timeEnd(); //end time