Skip to content Skip to sidebar Skip to footer

What Is The Difference Between If(!!condition) And If(condition)

I often see code that uses !!condition as opposed to just the regular condition. I.e.: if(!!value){ doSomething(); } versus: if(value){ doSomething(); } What is the funca

Solution 1:

Technically nothing. The double bang !! type converts value to a boolean - something the if statement does when it evaluates value anyway.

In the code you have posted, the !! is useless and serves no purpose.


Solution 2:

This is just a more explicit way to test the "truthiness" of a value.

The following will "cast" value to a boolean.

!!(value)

For example, a non-empty string

!!"a" // true

Another example with an empty string

!!"" // false

However, if you simply test a value directly using

if (value) // ...

then the following values are false in JavaScript

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

everything else is true


Solution 3:

The !! ensures the resulting type is a boolean (true or false).

javascript:alert("foo") --> foo

javascript:alert(!"foo") --> false

javascript:alert(!!"foo") --> true

javascript:alert(!!null) --> false

They do this to make sure $('row') isn't null.

It's shorter to type than $('row') != null ? true : false.


Post a Comment for "What Is The Difference Between If(!!condition) And If(condition)"