Hacker News new | ask | show | jobs
by MichaelApproved 3737 days ago
! -> "not truthy". So !! means "not 'not truthy'" which is truthy.

Truthy is something that isn't exactly a true boolean but will equate to true(thy) when evaluated with this type of comparison. Things like undefined, null, and empty string will not be truthy.

More info on what's truthy (for JavaScript at least) is here http://james.padolsey.com/javascript/truthy-falsey/

edit: typically, if you want to test for truthy, you'll just evaluate it like so

if (my_object) { //truthy }else{ //not truthy }

Does anyone know a time when you'd use !! instead of just the object in the evaluation? I'm not a Ruby dev, so I don't know specific cases for needing !!

3 comments

One typical use for !! in JavaScript or Ruby is where a function/method returns a boolean value that indicates the presence or absence of an object.

You could just use:

  return myObject;
Since that value will be truthy or falsy, any code that tests it will generally work, as your if statement example demonstrates.

But there are two advantages to doing this instead:

  return !! myObject;
1) Now you are returning an actual boolean value, not just a truthy/falsy value.

2) Sometimes more importantly, you are now releasing this function's reference to the object, instead of possibly keeping that reference around much longer than needed and preventing it from being garbage collected.

Generally when you prepare a value for serialization. In my ~8 years of Ruby I've only used !! a few times. I think all those times had to do with configuration and/or serialization. For example:

```

    my_option = !!ENV[MY_OPTION] # is false when not set
    puts "my_option is: #{my_option}"
```
Yep, I thought it was a common enough idiom in Ruby as well that it might belong on the list!