+ 1
What is different betweeñ for loop and while loop
6 Respuestas
+ 11
"for" is mainly used to iterate through arrays........
+ 4
A 'for' loop implemente implicitly a counter, than a 'while' loop don't:
for ( var i = 0; i < 10; i++ ) { /* the loop code */ }
... is equivalent to a 'while' loop with an explicit implementation of a counter:
var i = 0;
while ( i < 10 ) {
/* the loop code */
i++;
}
So, a 'for' loop is better adapted when you know the number of iteration, while 'while' loop is better adapted to not-known number of iteration and/or infinite...
The other syntax of a 'for' loop is with the 'in' keyword:
var o = { 'x': 10, 'y': 42 };
for ( var k in o ) {
alert( k + ' : ' + o[k] ); // alert successively 'x : 10' and 'y : 42'
}
... can iterate on object properties, or array index, in a shorthand writting ^^
+ 3
a for loop iterates a given number of times, and a while loop iterates until something specified happens
+ 2
A for loop and a while loop basically iterates for a number of times while the condition is true. You can specify the number of iterations you want in both (as opposed to what @just4 said). One difference is the way they are constructed. A while loop has two semicolons in between a parenthesis. The left is for initialization, center is for the condition and the right is for afterthought. A while loop only gives for the condition(s) in its parenthesis. For example:
// for loop
for (var a = 0; a < 10; a++) {
console.log(a);
}
// while loop
var a = 0;
while (a < 10) {
console.log(a);
a++;
}
Both loops do the same thing, except that on some machines, their execution time vary, making one more optimised than the other.
A for loop can also iterate for a number of times until a specified condition is true. The condition in the above loop is `a < 10` meaning while a is less than 10. What I think is the truth is that for every possible use case for any of the two loops, the other can also be used. But, one might outperform the other, and when you're going for readable, one might be neater. Feel free to use any.
+ 1
"for" when you know how many iterations you want through the loop
or when you determine the two limits of the iterations
"while" when you dont know how many iterations you want
for example :
when you go to coffee from 10 to 11 (for)
for(the time is 10;the time<11;the time++)
you will leaf it when you earn 1000$ ()
while(you dont earn 1000$)
you still here;
**********************
if you have a mistake and make infinite loop
the operating system will end this matter
so if you decide to still until you earn the money
the coffee will close
- 1
The biggest difference i can spot is the for loop will mainly be used for numeric looping
The while loop can be used for both numeric and boolean looping
eg
for(int a,a<10;a++){} is the same as
while(a<10){
.......
a++
}
we can also do boolean looping
while(false){......}