0

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!");
}
Nick
  • 138,499
  • 22
  • 57
  • 95

2 Answers2

2

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

Louay Al-osh
  • 3,177
  • 15
  • 28
1
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

Trajano Roberto
  • 179
  • 2
  • 7
  • "*since we are unsure variable type that foo() return,s the comparison will not work*" the comparison is not done before the code is ran based on what the function *might* return. It's done based on what it *does* return. `foo = () => Math.random() < 0.5 ? true : "bar"` will also leave us unsure what the return value is but that will not affect the comparison - if a `true` is returned, then `true == true` is still `true. – VLAZ Feb 02 '21 at 07:21
  • do not mix different variable types for a function return value; stick to bool; HTH traja47 – Trajano Roberto Feb 03 '21 at 00:28