1

For example suppose I have

var myVar;

If I do

console.log((myVar != undefined) && true);

It returns false as expected. Is it possible to do something closer to

console.log(myVar && true);

It's much less verbose. At the moment the above returns undefined I would like false.

deltanovember
  • 42,611
  • 64
  • 162
  • 244

2 Answers2

4

If I'm understanding you correctly, you want to turn undefined and false into false and true into true. If so, this should work fine:

console.log(!!myVar);

Each ! converts the value to a boolean and returns the opposite. The opposite of the opposite is the same as the original, except for that "converts to a boolean" part, which is exactly what you want.

For more information, see this question.

Community
  • 1
  • 1
icktoofay
  • 126,289
  • 21
  • 250
  • 231
2

One way to drag a boolean out of a "truthy" or "falsy" value is to use !!

console.log(!!myVar);
rjz
  • 16,182
  • 3
  • 36
  • 35