+ 1

JS: What’s the difference between while and if?

I’ve never really used the while statement because I didn’t really see the need to do so. But I’ve used if(and for) statements almost all the time. Today I decided to know more about the while statement, but on the examples I’ve seen on w3School and on videos, it looks similar to the if statement. What’s the difference and when do I need/should use the while statement?

15th Mar 2020, 6:18 AM
Ginfio
Ginfio - avatar
6 Answers
+ 8
In fact, the for loop is essentially a while loop with an initializer and incrementer. See example: for(initializer; conditional exp; incrementer) { // execute this block when true... } ---- initializer; while(conditional exp) { // execute this block when true... incrementer; } ---- Or, more specifically: for(let i = 0; i < 10; i++) { // execute this block while i is less than 10... } ---- let i = 0; // initializer while(i < 10) { // execute this block while i is less than 10... i++; // incrementer } Hopefully these make better since now.
15th Mar 2020, 7:58 AM
David Carroll
David Carroll - avatar
+ 7
Ginfio Interesting... I never considered just how similar the if(...) and while(...) statements appear on the surface. They both follow the same structure: if(conditional exp) { // execute this block when true... } while(conditional exp) { // execute this block when true... } The difference is the block for the while(...) statement will execute zero or more times as long as the conditional expression remains true. The block for the if(...) statement, on the other hand, will only execute zero or one times in the current context depending on if the conditional expression is true. You can, therefore, think of the while(...) statement as similar to an if(...) statement that runs like a loop.
15th Mar 2020, 7:56 AM
David Carroll
David Carroll - avatar
+ 6
While is looping statement and if is conditional statement. While loop will work untill condition satisfy and if will work when condition will satisfy. while statement is not same as if statement. for example: var x = 0; while(x < 10) { //works till x is less than 10 x++; Console.log(x); // will print value 1 to 10 } if(x < 10) { //works when x is less than 10 Console.log(x); // will print only 0 }
15th Mar 2020, 6:23 AM
AÍąJ
AÍąJ - avatar
+ 3
Kinda like the difference between a one-off payment and a recurring payment, or a one-off meeting and a recurring meeting when certain criteria are satisfied.
15th Mar 2020, 1:21 PM
Sonic
Sonic - avatar
+ 2
David Carroll oh, I see, now. The while statement is kind of like combination of for() and if(). It tests the condition, then if true it loops ... Makes sense.
15th Mar 2020, 11:28 PM
Ginfio
Ginfio - avatar