Reputation: 2275
I am doing an exercise on an online course to learn Javascript. This is only the first one and I am having issues, so I really want to understand it before I progress.
The question is this:
complete the while loop in the editor so it will print out "I'm learning while loops!". Do this by adding the condition between the parentheses—don't change line 5, or you could get an infinite loop!
The code is:
var understand = true;
while(){
console.log("I'm learning while loops!");
understand = false;
}
I tried adding this to the condition:
while(understand === 0){
But I am getting this error
Oops, try again. It looks like you didn't print the string to the console. Check your loop syntax!
What am I doing wrong in my condition? Could someone please elaborate, so I can learn the key fundamentals to this. Thanks!
The example before this exercise:
var coinFace = Math.floor(Math.random() * 2);
while(coinFace === 0){
console.log("Heads! Flipping again...");
var coinFace = Math.floor(Math.random() * 2);
}
console.log("Tails! Done flipping.");
Edit---update:
You may have noticed that when we give a variable the boolean value true, we check that variable directly—we don't bother with ===. For instance,
var bool = true;
while(bool){
//Do something
}
is the same thing as
var bool = true;
while(bool === true){
//Do something
}
but the first one is faster to type. Get in the habit of typing exactly as much as you need to, and no more!
If you happen to be using numbers, as we did earlier, you could even do:
Upvotes: 0
Views: 1933
Reputation: 3627
It's while(understand === true)
Because the loop will fire the first time, as understand
is already set to true. Then, as it's firing, it will set understand
to false- so the next time it tries to fire the loop the condition will fail and it won't continue. This way, you're getting one execution of the loop- thus printing only one time.
Upvotes: 2
Reputation: 703
If you had code that looks like this
while(true){
console.log("I'm learning while loops!");
understand = false;
}
you would get an infinite loop! The loop would just keep going because the conditional will always be true. Now if only there were some way, like a variable in the conditional, to make the conditional false.
Upvotes: 0