Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Pitfalls with Assigning Falsy Values in Defaults?

Tags:

javascript

Is there anyway that we can deal with falsy values in || operators that are lazily evaluated?

So, for example if we have:

function isOldEnough(age) {
   age = age || 18;
   return age;
}

isOldEnough(0) // returns 18 because 0 is falsy

In ES6, you can simply declare it like

function isOldEnough(age = 18) { ... }

Is there anythning we can do in ES5 to avoid this issue?

like image 425
Emma Ramirez Avatar asked Dec 22 '15 10:12

Emma Ramirez


People also ask

What are the Falsy values in JavaScript?

There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.

Which value is not Falsy in JavaScript?

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .

What is a 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.


1 Answers

Something like (if I understood correctly):

function isOldEnough(age) {
  var age = typeof age === "number" ? arguments[0] : 18;
  return age; 
}

isOldEnough(null) // returns 18
isOldEnough("") // returns 18
isOldEnough(undefined) // returns 18
isOldEnough(0) // returns 0

Could be further improved with checking if age is equal to or greater than zero etc

like image 67
dsgriffin Avatar answered Oct 11 '22 02:10

dsgriffin