John Au-Yeung

Folgen Sie

5.August 2019 · 2 min lesen

Es ist einfach, alles in JavaScript in einen booleschen Wert umzuwandeln. Truthy-Werte werden in true und Falsy-Werte in false konvertiert. Es gibt 2 Möglichkeiten, Variablen in einen booleschen Wert zu konvertieren., There is the Boolean function, and there is the !! shortcut.

There are 6 kinds of falsy values:

  • false
  • 0
  • empty string: "" , '' , or ``
  • null
  • undefined
  • NaN — not a number value

Anything else is truthy.,

Wenn Sie sie als boolesch auswerten, erhalten Sie:

im Gegensatz zu wahrheitsgemäßen Werten wie Objekten, die alles andere als die obigen Werte sind:

Boolean({}) // true
Boolean(true) // true
Boolean() // true

Sie können auch die !! shortcut to cast to Boolean, the right ! cast the variable into a boolean and negate the value, and the left ! negate it back to the actual boolean value.,

!!(false); // false
!!(0); // false
!!(""); // false
!!(''); // false
!!(``); // false
!!(undefined); // false
!!(null); // false
!!(NaN); // false

Similarly for truthy values:

!!({}) // true
!!(true) // true
!!() // true

With shortcut evaluation, boolean ANDs and ORs are evaluated up to the first truthy value:

const abc = false && "abc"; // false, since false is false and "abc" is trueconst def = false || "def"; // true, since false is false and "def" is true