149

Possible Duplicate:
What is the !! operator in JavaScript?
What does !! (double exclamation point) mean?

I am going through some custom JavaScript code at my workplace and I am not able to understand the following construct.

var myThemeKey = (!!$('row') && $('row').hasClassName('green-theme')) ? 'green' : 'white';

I understand everything on the above line except !! operator. I assume that it is a NOT operator and NOT of NOT is the original value but why would someone do a NOT of NOT?

Can someone please help me understand what is happening on the above line of code?

Community
  • 1
  • 1
stirfries
  • 1,734
  • 2
  • 11
  • 11
  • http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript – Eric Fortis Sep 17 '11 at 05:48
  • Repeat of http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript – Surreal Dreams Sep 17 '11 at 05:48
  • http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript – Josh Sep 17 '11 at 05:48
  • The short answer is that it converts the value to boolean - so if it has non-zero it's true, else false. – Surreal Dreams Sep 17 '11 at 05:50
  • @stirfries - Welcome to stackoverflow. This question has already been asked before, so your question will probably be closed. When it does just follow the links to the first time the question was asked and you should find the info you're looking for. – Richard JP Le Guen Sep 17 '11 at 05:51
  • In the future, do not start titles with "Please help me understand..." This gives only very bad results in the possible duplicate search list while you're typing in the question. Just make it a clear, concrete and to-the-point question. Then you'll get results like as right now in the "Related" section on the right column (with among others some duplicate questions with the answers you're looking for ;) ). – BalusC Sep 17 '11 at 05:53
  • @Richard JP Le Guen - Thanks...I appreciate the directions. – stirfries Sep 17 '11 at 06:01
  • @BalusC - Thanks for the tips...I will follow the same in the future. – stirfries Sep 17 '11 at 06:02

1 Answers1

245

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.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • 72
    I'd just like to add that this is a double negation: `!` returns `true` if the object is *null*, *undefined* or an empty string and `false` otherwise. If you negate it again you get `true` for values that exist and `false` for the ones that do not. – Telmo Trooper Mar 20 '20 at 16:38
  • Also !!NaN return false – Luca Davanzo Apr 27 '21 at 12:22