Reputation: 169
Again this will be a bit of a newbie question, im just trying to get clear in my head how javascript interprets Boolean expressions.
okay so say i have the following bit of code:
var boolean = true;
while(boolean){
boolean === false;
};
This goes into an infinite loop due to the use of the identical === operator. Is this because javascript stores the boolean expression "true" as digit "1" while using the shorthand expression while(boolean). So is while(boolean) actually interpreted as while(boolean === 1) rather than while(boolean === true)?
Upvotes: 0
Views: 570
Reputation: 1074168
Is this because javascript stores the boolean expression "true" as digit "1" while using the shorthand expression while(boolean).
No.
So is while(boolean) actually interpreted as while(boolean === 1) rather than while(boolean === true)?
No.
It loops forever because you're doing nothing to change the value of your boolean
variable within the loop. The line
boolean === false;
...has no effect; you're doing a comparison and not storing the result of it anywhere.
You seem to have =
and ===
confused. They do completely different things. Here's a rundown:
=
is the assignment operator. It's what you use to assign values to things. boolean = true;
assigns the value true
to the variable boolean
.
===
is the strict equality operator. It's used to see if two things are strictly equal ("strictly" = "without type coercion"). So a === b
evaluates true
if a
and b
contain values with the same type that are equivalent.
==
is the loose equality operator. It's used to see if two things are loosely equal ("loosely" = "with type coercion"). So a == b
will evaluate true
if a === b
would be true or if a
and b
have different types but type coercion can convert one or the other to be the other's type. (The rules for this are complex, but for instance "" == 0
evaluates true
because ""
coerces to 0
.)
Upvotes: 4
Reputation: 856
= is the assignment operator. Writing
var bool = false;
means "set the variable named 'bool' to 'false'"
While === is a strict equality operator. Writing
bool === false;
checks if the variable 'bool' holds the exact value 'false'. It means "Does the variable 'bool' hold the value 'false'?"
It will return a boolean: true if bool holds the value false, false otherwise. In this case it returns true.
It goes into an infinite loop because 'bool' never changes value. To set it to true, use =
bool = true;
Upvotes: 0