5

I've recently started using double exclamation points !! before an object to make sure that it's not null and that it's not undefined and not an empty string, to make sure that I encompass all the different ways that a variable can be empty.

Is this necessary? It's hard to read, for instance: if(!!name) vs if(name)

Any opinions on this? I want my code to be safe and not get into conditions where a null pointer exception and other things can occur, but I also want my code to be readable.

Dexygen
  • 12,287
  • 13
  • 80
  • 147
reectrix
  • 7,999
  • 20
  • 53
  • 81

4 Answers4

7

No, there's no need at all for the double-bang if you're using the variable as the condition in an if. Simply if (name) is sufficient to ensure that name is not a falsy value. All object references are truthy; null is falsy.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
7

What you're doing is already done by JavaScript natively.

if( value ) { }

will evaluate to true as long as value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

Check out the toboolean conversions in the specification.

Bricky
  • 2,572
  • 14
  • 30
  • Does javascript also do this for ternary operators? For instance if I have `var hasName = name ? true : false;` – reectrix Oct 23 '16 at 19:25
  • hasName = name is assignment, not a boolean test but otherwise yes, because a ternary simply determines which output to use based on the conditional, which is evaluated in the same way. – Bricky Oct 27 '16 at 21:22
4

This is completely unnecessary unless you need a strict comparison to boolean true, for example:

switch (true) {
  case foo:

Should be

switch (true) {
  case !!foo:

Or alternatively, the verbose but more readable Boolean(foo) (don't use new with the primitive constructors). Note that opposite is not true, if you are testing for falsey values then it becomes a problem because 0, NaN and the empty string, which may be valid values, are falsey:

if (!foo) { // foo had better not be empty string or zero

However, JavaScript offers you an out here (that some frown on) involving loose equality, null and undefined are loosely equivalent to each other but not to any other falsey values:

null == undefined //true
null == NaN // false
undefined == '' // false
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
2

Totally and completely ... pointless, to use a small pun.

The if() autmotically converts the conditional value to a boolean.

The !! converts it a boolean as well.

Where !! is sometimes used is to force something to a boolean value..

Such as:

var hasElement == !!document.getElementById("zz");
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74