1.1 Intro To While Loops


#1

I tried looking through the Q&A here but didn't see it addressed. Does anyone know why in 1.1, the example sets coinFace === 0 but then in lesson 1.2, they are explaining that JavaScript understands 1 to be true and 0 to mean false? Doesn't that mean that coinFace is false and it shouldn't run at all or am I not understanding something?

Here is the code in lesson 1.1:

var coinFace = Math.floor(Math.random() * 2);

while(coinFace === 0){
console.log("Heads! Flipping again...");
var coinFace = Math.floor(Math.random() * 2);
console.log(coinFace);
}
console.log("Tails! Done flipping.");


#2

@goldiefish
I believe here coinFace is not a boolean variable, it is just a number, so what you have in the while loop is just checking whether the value of coinFace is 0. The number, not false or true.


#3

Be careful with this:

"=" is an assignment statement. (i.e. x=2 means "Make the variable x equal to 2")
"==" is a boolean operator (i.e. x==2 means "Does x equal 2?")

(for beginning you can see == and === as equal)


#4

can you give me more explanation on the difference between "==" and "==="?


#5

For short:

== only compares values

=== compares values + type

example:

if you have
double x = 1;
int y = 1;

if(x == y) //returns true because the value is the same
if(x === y) // returns false because the value is the same but the type not


#6

yes 0 means false, but here you're condition is coinFace ===0 and this check whether the two are equal is true so the loop is running.


#7

can you give me an example of when 0 means false? I don't understand the example in 1.2 because it say: When you use a number in a condition, as we did earlier, JavaScript understands 1 to mean true and 0 to mean false. but in the earlier example, the only time we use 0 is here:

while(coinFace === 0){

Here is the full code from 1.1:
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.");


#8

If you use a single value in a condition e.g.

if(1){
    code
}

then they would be interpreted in a truthy or falsy way meaning here 1 would mean true and also if use the lesser strict equal ==, 1== true would be true for example. But there is no reason that I know to use this, rather use boolean values in conditions or calculations that end up in a boolean value e.g. A == B, A > B, A<= B, aso.


#9

thank you, this makes a lot of sense


#10

okay got it. Thank you for the explanation.