What are Truthy and Falsy in JavaScript?

Tram Ho

What are Truthy and Falsy in JavaScript?

** This is a short article introducing Truthy and Falsy in JavaScript, a basic and extremely important concept in JS that not all new learners know. Here, let’s find out what it is, why it is important, and rarely use it. **

The concept of Truthy and falsy

  • JavaScript uses Type conversion (which converts data from one data type to another) to force any value into a Boolean value in a context that requires a Boolean value.
  • Truthy and falsy are values ​​that JavaScript when enforced to Boolean type, or in a Boolean context it will return true or false.

Values ​​are considered truthy: non-empty string, non-zero number and all objects. // Include both [] and {} because empty array and empty string are still objects.

Example of the Truthy value (it would be enforced to True in Boolean context and thus execute the If block):

Values ​​are considered falsy: undefined, null, false, 0, -0, 0n, NaN, ”.

Falsy value example (It will be cast to False in a boolean context and therefore ignore the If block.

Another example of Truthy and Falsy in a Boolean context. Here the || operator will return the left-hand side operand if the left-hand side is truthy and if the left-hand side is falsy, then if the left-hand side is falsy, it returns the right-hand-side operand (this is often used to provide default values). But it will also happen after some problems like below that you easily notice if you consider 0, ”, NaN as valid. As person.point here has the value 0 (falsy), it will return the right operand of undefined point that causes the unexpected result. As a fix, the nullish coalescing operator (??) is a new feature introduced in ES11 (ECMAScript 2020). According to the definition of MDN ?? is a logical operator that will return the right operand if the left hand side is null or undefined, and otherwise its left operand is returned. So if the value is 0, ”, NaN, it will still accept as valid values.

And that is a summary of Truthy and falsy in JavaScript, you can learn more here https://developer.mozilla.org/en-US/docs/Web/JavaScript .

Share the news now

Source : Viblo