Tuesday, August 22, 2017

Truthy and Falsy: When All is Not Equal in JavaScript

JavaScript variables are loosely/dynamically typed and the language doesn't care how a value is declared or changed.

JavaScript-truthy-falsy

2017.07.12: This article has been updated to reflect the current state of the JavaScript ecosystem.

let x;
x = 1;   // x is a number
x = '1'; // x is a string
x = [1]; // x is an array

Seemingly different values equate to true when compared with == (loose or abstract equality) because JavaScript (effectively) converts each to a string representation before comparison:

// all true
1 == '1';
1 == [1];
'1' == [1];

A more obvious false result occurs when comparing with === (strict equality) because the type is considered:

// all false
1 === '1';
1 === [1];
'1' === [1];

Internally, JavaScript sets a value to one of six primitive data types:

  • Undefined (a variable with no defined value)
  • Null (a single null value)
  • Boolean (true or false)
  • Number (this includes Infinity and NaN - not a number!)
  • String (textual data)
  • Symbol (a unique and immutable primitive new to ES6/2015)

Everything else is an Object — including arrays.

Truthy and Falsy

As well as a type, each value also has an inherent boolean value, generally known as either truthy or falsy. Some of the rules are a little bizarre so understanding the concepts and effect on comparison helps when debugging JavaScript applications.

The following values are always falsy:

  • false
  • 0 (zero)
  • '' or "" (empty string)
  • null
  • undefined
  • NaN (e.g. the result of 1/0)

Everything else is truthy. That includes:

  • '0' (a string containing a single zero)
  • 'false' (a string containing the text "false")
  • [] (an empty array)
  • {} (an empty object)
  • function(){} (an "empty" function)

A single value can therefore be used within conditions, e.g.

if (value) {
  // value is truthy
}
else {
  // value is falsy
  // it could be false, 0, '', null, undefined or NaN
}

Loose Equality Comparisons With ==

Unexpected situations can occur when comparing truthy and falsy values using the == loose equality:

== true false 0 '' null undefined NaN Infinity [] {}
true true false false false false false false false false false
false false true true true false false false false true false
0 false true true true false false false false true false
'' false true true true false false false false true false
null false false false false true true false false false false
undefined false false false false true true false false false false
NaN false false false false false false false false false false
Infinity false false false false false false false true false false
[] false true true true false false false false true false
{} false false false false false false false false false true

Continue reading %Truthy and Falsy: When All is Not Equal in JavaScript%


by Craig Buckler via SitePoint

No comments:

Post a Comment