Posted almost 3 years ago. Visible to the public. Repeats.

LoDash: isBlank and isPresent mixins

When you need to check a value for presence, don't rely on JavaScript since it considers 0 or "0" false. Also don't rely on LoDash's _.isEmpty:

Copy
if ('0') { ... } // false if (0) { ... } // false
Copy
if (!_.isEmpty('0')) { ... } // true (= good) if (!_.isEmpty(0)) { ... } // false (= not good)

This is because isEmpty it is only meant for objects with a length.

While the name implies that it's meant only for collections, you probably still want something like isBlank or isPresent that return true/false for objects humans would normally consider blank or present.

Here is some CoffeeScript that provides _.isBlank and _.isPresent via LoDash/Underscore.js mixins:

Copy
_.mixin isBlank: (object) -> switch typeof object when 'boolean' then false when 'function' then false when 'number' then isNaN(object) else _.isEmpty(object) isPresent: (object) -> !_.isBlank(object) , chain: false

Use them like this:

Copy
_.isBlank(0) // false _.isBlank(23) // false _.isBlank('') // true
Copy
_.isPresent(null) // false _.isPresent(NaN) // false

The chain: false option above also allows to use them as terminal methods:

Copy
_(23).isBlank() // false _(23).isPresent() // true

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Author of this card:

Avatar
Arne Hartherz
Last edit:
3 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandropedia