1

in some es6 code I see following:

let layer_combined = layers.map(getLayer).filter(l => !!l);

what is the meaning of !! in the filter() return?

Dexygen
  • 12,287
  • 13
  • 80
  • 147
Anatol
  • 1,923
  • 6
  • 26
  • 55

1 Answers1

0

It's a way of casting to a boolean with double negation.

A singular ! negation produces a true/false value, but it's the opposite of what you want. Double negation produces a true/false value which matches the original intent.

Try it:

!!0 // false
!!1 // true
!!"test" // true
!!null // false
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 4
    This question is a blatant duplicate from 9.5 years ago, less than a year after Stackoverflow started. It should be closed as a duplicate, and not answered. – Dexygen Nov 01 '18 at 18:45
  • @GeorgeJempty Answering a question twice in ten years should not be considered a problem. – tadman Nov 01 '18 at 18:46
  • @GeorgeJempty you're right its a duplicate. will close it. thanks for providing the link. – Anatol Nov 01 '18 at 18:46
  • 1
    and thanks to @tadman ! – Anatol Nov 01 '18 at 18:47
  • @tadman sorry for one more on this. if l is an object let `l = 0 console.log(!!myobject);` one would use !! just to cast 0 to a boolean false, right? If it´s something like `l = {thanks: 'to tadman'}` it would be boolean true. If so I don't really see the need for this in given filter function. – Anatol Nov 01 '18 at 18:59
  • 1
    @tadman *Any* duplicate is a problem. Furthermore, this has been duplicated more than once, I just did due diligence and found the oldest one – Dexygen Nov 01 '18 at 19:10
  • @GeorgeJempty I strongly disagree. Duplicates are not a problem. "Closing as duplicate" is just an easy way to answer a question if it keeps getting asked over and over and over. If someone wants to take the time to answer a duplicate, let them. If nobody has the time, close as duplicate. – tadman Nov 01 '18 at 23:57
  • @tadman Disagree as much as you want, it just shows you don't know how StackOverflow is supposed to work – Dexygen Nov 02 '18 at 00:50