Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding JavaScript Truthy and Falsy

Tags:

javascript

Can someone please explain JavaScript Truthy and Falsy, using the below sample data. I have read other threads but still confused.

var a = 0;  var a = 10 == 5;  var a = 1;   var a = -1; 

From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy - is this correct?

like image 932
tonyf Avatar asked Feb 26 '16 03:02

tonyf


People also ask

What is Falsy and truthy?

Truthy values are values that evaluate to True in a boolean context. Falsy values are values that evaluate to False in a boolean context. Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None , and False .

How do you know if its truthy or Falsy?

To check if a value is truthy, pass the value to an if statement, e.g. if (myValue) . If the value is truthy, it gets coerced to true and runs the if block. Copied! In our if statement, we check if the value in the myVar variable is truthy.

What is JavaScript Falsy?

A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context. JavaScript uses type conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops.

Is {} truthy in JavaScript?

Every other value is considered truthy. It's important to remember that this applies to all JavaScript values, even ones that might seem falsy, such as empty arrays ( [] ) or empty objects ( {} ). You can check a value's truthiness using either the Boolean() function or a double negation ( !! ).


2 Answers

From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy’s - is this correct?

No.

  1. var a = 0;

    Number zero is falsy. However, note that the string zero "0" is truthy.

  2. var a = 10 == 5;

    This is same as var a = (10 == 5);, so this is falsy.

  3. var a = 1;

    var a = -1;

    Any non-zero number including negative numbers is truthy.

Quoting from MDN

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

List of falsy values in JavaScript:From MDN

  1. false
  2. null
  3. undefined
  4. 0
  5. NaN
  6. '', "", ``(Empty template string)
  7. document.all
  8. 0n: BigInt
  9. -0
like image 95
Tushar Avatar answered Sep 27 '22 22:09

Tushar


There's a simple way to check, which you can use now and forever:

function truthyOrFalsy(a) {     return a ? "truthy" : "falsy"; } 

To wit:

> truthyOrFalsy(0) "falsy" > truthyOrFalsy(10 == 5) "falsy" > truthyOrFalsy(1) "truthy" > truthyOrFalsy(-1) "truthy" 

Also see a list of all falsey values in JavaScript.

like image 25
Claudiu Avatar answered Sep 27 '22 23:09

Claudiu