Siluveru Kiran Kumar
Siluveru Kiran Kumar

Reputation: 799

what is the difference between Boolean('') is false and Boolean(new String(''))?

I have a doubt that both are strings why getting different Boolean values Boolean('') is false and Boolean(new String(''))?

Upvotes: 0

Views: 1946

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

The Boolean function returns true for all object references. new String("") creates a string object. In contrast, "" is just a string primitive; Boolean returns false for a blank string primitive.

When called as a function (rather than as a constructor), Boolean returns the result of the spec's ToBoolean abstract operation:

The abstract operation ToBoolean converts argument to a value of type Boolean according to Table 9:
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
|                 Table 9: ToBoolean Conversions                  |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Argument Type | Result                                          |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Undefined     | Return false.                                   |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Null          | Return false.                                   |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Boolean       | Return argument.                                |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Number        | If argument is +0, −0, or NaN, return false;    |
|               | otherwise return true.                          |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| String        | If argument is the empty String (its length is  |
|               | zero), return false; otherwise return true.     |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Symbol        | Return true.                                    |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Object        | Return true.                                    |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

As you can see from the last row in the table, anything that's an object will result in true.

Upvotes: 3

Ele
Ele

Reputation: 33726

  1. The following values are coerced to false because are falsy values: '', NaN, undefined, null, 0.
  2. Everything else will be coerced to true because are truthy values.

What you're trying to do with:

Boolean('') // Coercing a primitive empty string (falsy).

And with the following:

Boolean(new String('')) // Coercing an object (truthy).

Upvotes: 0

Related Questions