The first case will execute, while the latter one will not. Can you please explain this to me?
function foo() {
return "bar";
}
if (foo()) {
console.log("This works!");
}
if (foo() == true) {
console.log("This does not work!");
}
The first case will execute, while the latter one will not. Can you please explain this to me?
function foo() {
return "bar";
}
if (foo()) {
console.log("This works!");
}
if (foo() == true) {
console.log("This does not work!");
}
The first case foo()
is implicitly converted to boolean like if(Boolean(foo()))
which is equal to if(Boolean("bar"))
where any string that has a length bigger than 0
is converted to true
(considered truthy
value)
in the second case you are comparing "bar"
to true
where the ==
will try to convert one value type into the other it will fail that is why it's evaluated into false
in the second case
you can read from ydkjs book the full explanation
function foo() {
return "bar";
}
this function returns a variable type "bar"
if (foo() == true) {
console.log("This does not work!");
}
since we are unsure variable type that foo() return,s the comparison will not work //if (foo() == true) {
find out the variable type the function returns, and make the necessary comparison
HTH traja47