It is important to know fundamentals to understand why Javascript does the things it does. You will know why things aren’t working, know the falsy values will help you to debug and you will become a better developer.


Falsy

The falsy values are considered false when encountered in a Boolean context, the values in Javascript have an implicit coercion, it uses Type Conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops, so then we could say that the values in Javascript have a inherent Boolean value based on the context, it is really important to know what those values would be evaluated in the coercion true or false, especially when it comes to conditionals.

This are the falsy values in javascript:

if (false)
if (undefined)
if (null)
if (NaN)
if (0)
if (-0)
if ("")
if ('')
if (``)

everything else is considered truthy.

Checkout the info about Falsy at MDN


Truthy

The truthy values are considered true when encountered in a Boolean , like the falsy. All values are truthy unless they are defined as falsy, Remember if it’s not on the false list, it’s true!

Here are some values that you might have thought was false, but it actually evaluates to true:

if (true)
if ('false')
if ({})
if ([])
if (42)
if (-42)
if ('0')
if (new Date())
if (function(){})
if (Infinity)
if (-Infinity)

Checkout the info about Truthym at MDN


Conditional Statements Shorthand

Every value in Javascript will be coerced to true or false in boolean contexts. Keeping that in mind we can shorten our conditional in the if statement.

// Don't do this
if (value === false)

// Much better
if (!value)

You can also do the same to shorten the condition in ternary operators.

// Don't do this
value === false ? 'no' : 'yes';

// Much better
!value ? 'no' : 'yes';

Logical Operators

Like we see in the Javascript Object Literal Conditional Properties . In JavaScript, expressions using the && and || operators get checked for possible short-circuit evaluation .

&& operator will only evaluate to true if both conditions are truthy. If the first one if falsey, then the second condition won’t even get evaluated. the || operator will only evaluate to false if both condition are falsey. If the first condition is truthy, the second won’t get evaluated. Additionally, the && and || operators actually return the value of the last expression that gets evaluated in the statement.

const firstOr = [] || 'hi';
console.log(firstOr);
// expect output: []

const secondOr = '' || 'hi';
console.log(secondOr);
// expect output: 'hi'
const firstAnd = [] && 'hi';
console.log(firstAnd);
// expect output: 'hi'

const secondAnd = '' && 'hi';
console.log(secondAnd);
// expect output: ''