-4

What’s the difference between:

!!(obj1 && obj2);

and

 (obj1 && obj2);
Maizere Pathak
  • 303
  • 1
  • 9
  • 3
    `console.log('a' && 'b', !!('a' && 'b'));` --- why didn't you try before ask? yeah, I know, it's boring, but it takes 10 seconds to check yourself. -1 for being lazy – zerkms Feb 06 '13 at 03:57

2 Answers2

1

The first will potentially return a string or an object, the second will return a boolean.

Because objects can be truthy in javascript, A && B will return the value of B if it is truthy, which may be an object. But using !! will cast it to a boolean because the !B will convert it to true or false, and the second ! will move it to the correct boolean value

An example where the two will differ:

var a = "test", b ="example"
var ex1 = ((a && b)   === true)  // false
var ex2 = (!!(a && b) === true)  // true
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
0

There is none.

In general, !! is used to cast to boolean without using a function call, similar to how 0^ can be used to cast to integer, ""+ can be used to cast to string, etc.

However, in this case, assuming it's inside an if statement, there's no difference at all since the if implicitly "casts" to a boolean to see if it's true or not.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592