Falsy values in Javascript

2019, Aug 29

How to deal with falsy values in Javascript !

Javascript has it’s own way of dealing with values. Developers from Java or any object oriented programming background get confused while dealing with falsy values. That may leads to some mistakes. Let’s try to understand, what is the meaning of falsy values in Javascript.

TABLE OF CONTENTS

  1. What are the falsy values in JavaScript
  2. Ways of comparing falsy values
  3. Dealing with falsy values in array
  4. Short-circuit evaluation
  5. Conclusion

What are the falsy values in JavaScript

A falsy value is a value that translates to false when evaluated in a Boolean context.

  • false (boolean false)
  • null
  • undefined
  • 0 (number zero)
  • ‘’ or “” (empty string)
  • NaN

If we print in console by doing Boolean() then we will get false for all falsy values.

console

Comparisons:

Many developers use to compare explicitly with these falsy values, which is not at all require.

Bad code:

if (someValue === null) {} 
if (someValue === undefined) {}
if (someValue === '') {} 
if (someValue === "") {} 
if (someValue === 0) {} 
if (someValue === NaN) {}

We don’t have to compare like this. Instead of this we can do like

if (someValue) {} 

If the “someValue” belongs to these falsy values then it will give “false” and execute the false condition.

Even I have seen some of the developers assign true and false (boolean) values on basis of the result.

Bad Code:

const result = getValue(response);//fetching required value from API const
isResult = result ? true : false;

When “result” variable itself can give true or false on basis of the value it gets from response then why we need to create separate variable and assign the boolean value???

Falsy values in Array:

If we have an array with falsy values and we are filtering it on basis of Boolean then:

const noFalsyAndZero = [
  null,
  0,
  1,
  -2,
  50,   undefined, 
  true, 
  false, 
  '',
  NaN
].filter(Boolean);
// [ 1, -2, 50, true ]

console-2

We can see that it is also removing the 0(zero). We have to take care while dealing with array in such situation.

const noFalsyButWithZero = [
  null,
  0,
  1,
  -2,
  50, 
  undefined, 
  true, 
  false, 
  '',
  NaN
].filter(value => value === 0 || Boolean(value));
// [ 0, 1, -2, 50, true ]

devtool

Here, we have added extra logic to add 0(zero) to the result. Lets take the example of array of an object.

const persons = [
  {
    name: null,
    age: 20,
    address: []
  },
  {
    name: "Alex",
    age: 29,
    founders: []
  },
  {
    name: "Mallik",
    age: 10,
    address: []
  },
  {
    name: "Renu",
    age: 50,
    address: []
  },
  {
    age: 25,
    address: []
  }
];
const personNames = persons.map(person => person.name);
// [null, "Alex", "Mallik", "Renu", undefined]

console-4

Let say, after getting names we are converting it to the uppercase.

const makeNameUpperCase = name => name.toUpperCase();
const personNamesInCaps = personNames.map(makeNameUpperCase);
// TypeError: Cannot read property 'toUpperCase' of null

console-5

“toUpperCase()” will throw error when we use it for any null or undefined values. We can handle it by filtering out the array on basis of boolean values.

const personNamesInCaps = personNames
                           .filter(Boolean)
                           .map(makeNameUpperCase);
// [ "ALEX", "MALLIK", "RENU" ]

console-6

Short-circuit evaluation:

Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument is not sufficient to determine the value of the expression. when the first argument of the AND (&&) function evaluates to false, the overall value must be false; and when the first argument of the OR (||) function evaluates to true, the overall value must be true. (Copied)

Lets check this example:

const person = {
      name: "Alex",
      role: "admin"
};
const userRole = person.role || 'user';
console.log(userRole); 
// "admin"

Here, it will check person.role while evaluating the value for the “userRole”. If person.role is not a falsy value then it will assign the person.role value i.e “admin”. In case, person.role is a falsy value then it will assign “user” to the “userRole” variable.

const person = {  name: "Alex",  role: ""};//role may be null or undefined
const userRole = person.role || 'user';
console.log(userRole); 
// "user"

Conclusion:

There are some advantages and also disadvantages. One thing I see here is, it affect the readability but reduce the lines of code.