Note the comparison operator. = by itself is assignment.
The conditional argument of an if statement always yields a boolean so direct comparison to a boolean is redundant. We only need to test for truthiness
In all the examples provided so far for conditional statements, the condition is either ‘if (true)’ or ‘if (false’. However, in the instructions, I am told to write ‘if (sale)’. Is it only possible to make the condition something other than true/false if the previous line has a boolean variable? Thanks
The variable needn’t be a boolean value, but is set to one for the example. As illustrated, the action in the if statement block will not execute since the variable is set to false.
if (condition) {
// action code to run only if condition evaluates to true
}
In the above, condition can be any expression, not necessarily an explicit boolean primitive. Since the code branch is only followed when the condition is true, we would never write,
I didn’t get it sorry. Can you explain me more… Do you mean that sale===true doesnt implying sale to be boolean?
Also tell me if booleans are like numbers and we can’t write them quotes like “true”. we write numbers as 6 (without quotes) so will “true” make true from boolean to string…Are boolean logical operators like arithmetic operators
OKay! Formerly, the interchange between the 2 styles created a bit of confusion about which is correct or not in certain scenarios. But it’s clearer now that direct comparison to a boolean is equally correct, albeit old-fashioned and/or redundant.
Thank you so much. The lession that directs here was a little vague as to the relevancy of if… else being an indicator of truthiness. That’s the perfect Colbertism for understanding this lession.
I do believe that if(condition) and if(condition === true) are not identical
if(condition) is checking if the condition evaluates to true (if it is a truthy value) while if(condition === true) is checking if the condition is identical to the primitive boolean true
let name = "Samy";
if(name) {
console.log("This line will get executed");
}
if(name === true) {
console.log("This line will not get executed");
}
It is rare that we would actually need to test for true, since a truthy test will have the same outcome. If it is imperative that it be true then one supposes test for the value identity, but I fail to see an actual need for that level of exactness.
Not so. It can be used on any value, number, string, object. The evaluation is whether it is truthy or falsy. In the case above, 2 is truthy.
Falsy values include,
0 => zero
'0' => zero represented in string form
'' => the empty string
null => the null object
undefined => undefined variable or return
NaN => Not a Number