Using an object instead of a Boolean alter application flow

Viewed 51

I was reading on "Profissional Javascript for web developer" book and didn't understand this part when author saying :

"Mistakenly using an object instead of a Boolean can drastically alter the flow of your application."

enter image description here

can anyone explain it a little more with an example ... thanks

2 Answers

It is called automatic type coercion. When evaluating an expression, JS automatically coerces the variables to a type which can be evaluated. What the author saying is that, if you use an object in a boolean evaluation, the object coerced to a boolean type - always resulting true.

See the following snippet:

//An empty object
let o = {};

if (o)
  console.log(true)
else
  console.log(false);
  
  
 //Let's give it a value 
 o.status = false;
 
 if (o)
  console.log(true)
else
  console.log(false);

The result of the above code is true true. This is due to the fact that an empty object will be coerced to a truthy value - and no matter what falsy values an object have it still evaluates to true.

It's primarily warning you against performing equivalency operators against objects which can easily 'accidentally' return true:

let myTestBoolean = false;
let myTestObject = { result: false };

if (myTestBoolean) {
  console.log("boolean is true");
} else {
  console.log("boolean is false");
}
//results in "boolean is false"

if (myTestObject) {
  console.log("object is true");
} else {
  console.log("object is false");
}
//results in  "object is true"

Related