0

I have a method as follows. what is mean by !! and what is happening here?

private isDxsLoaded(): boolean {
    return !!this.dx;
}
SamL
  • 23
  • 1
  • 7
  • Use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding [boolean primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures). The conversion is based on the "truthyness" or "falsyness" of the value (see [truthy](https://developer.mozilla.org/en-US/docs/Glossary/truthy) and [falsy](https://developer.mozilla.org/en-US/docs/Glossary/falsy).See [MDN JavaScript Reference - Logical Operators - Double NOT (!!)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT_(!)) – georgeawg Jan 21 '19 at 23:53

1 Answers1

3

In javascript you can have true and false statements, like known in most other languages but you can also have truthy and falsy.

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

https://developer.mozilla.org/en-US/docs/Glossary/Truthy

The ! operator is not. So

 return !false // will return true
 return !!false // will return false

So when we put that together:

this.dx propably holds some value, a text, an object or an array.

this.dx = 'mytext'

So the statement

if (this.dx) { } // is truthy because it contains strings

if (!this.dx) { } // is falsy

if (!!this.dx) {} // true

The function

private isDxsLoaded(): boolean {
    return !!this.dx;
}

Is supposed to return true or false, so instead of doing something like

private isDxsLoaded(): boolean {
  if (this.dx && this.dx.length > 0) {
    return true
  } else {
    return false
}

They are utalizing truthy/falsy statements with double not operator

return this.dx // would return a string or an object (i don't know what this.dx is)
return !this.dx // will return false
return !!this.dx // will return true

Basically the code is saying: If this.dx contains some value (string, objects, array, numbers (other than 0), then return true.

Bergur
  • 2,668
  • 8
  • 15