2

I came across with something like this today.(I thought that it would alert goodbye)

x = new Boolean(false);

if (x) {
  alert('hello');
}else{
    alert('goodbye');
}

I thought that was something like this(Which alerts goodbye):

x = false;

if (x) {
  alert('hello');
}else{
    alert('goodbye');
} 

I don't I understand how it works.

JRulle
  • 7,448
  • 6
  • 39
  • 61
Sergiti
  • 151
  • 3
  • 18

4 Answers4

3

You should look up the "truthy - falsy" properties of javascript. Here is an article. In the first case x is true, because it is a non-null and non-undefined object, hence it is truthy. In the second, x is a boolean type of false, which is falsy.

Some things to remember from the article:

The following values are falsy:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN (a special Number value meaning Not-a-Number!)

Everything else is truthy!

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
3

If you use typeof x you realize x is an object. Object are always true.

Most values convert to true with the exception of the following, which convert to false:

  • The empty string ""
  • null
  • undefined
  • The number 0
  • The number NaN
  • The Boolean false
Alex Char
  • 32,879
  • 9
  • 49
  • 70
3

That's an instance of the Boolean function, not a boolean primitive.

true and false in javascript are boolean primitives. When you use them with boolean operators, they behave as you would expect. For example true || false is true and true && false is false.

On the other hand, Boolean is a special function which can convert other data types into boolean's (among other things). When you call new Boolean(false), you're creating a Boolean object which contains the boolean primitive false. That's the critical distinction in this case.

In short,

  • if(new Boolean()) uses javascript's truthy value rules. It is an object which is not null, so it's "true".
  • if(false) is a boolean primitive and actually checks for true/false.
just.another.programmer
  • 8,579
  • 8
  • 51
  • 90
2

new Boolean(false) returns an object which is not null. Non-null objects are always true.

reference

Community
  • 1
  • 1
JRulle
  • 7,448
  • 6
  • 39
  • 61