Read more

LoDash: isBlank and isPresent mixins

Arne Hartherz
November 13, 2014Software engineer at makandra GmbH

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:

if ('0') { ... } // false
if (0) { ... } // false
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

This is because isEmpty it is only meant for objects with a length Show archive.org snapshot .

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:

_.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:

_.isBlank(0) // false
_.isBlank(23) // false
_.isBlank('') // true

^
_.isPresent(null) // false
_.isPresent(NaN) // false

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

_(23).isBlank() // false
_(23).isPresent() // true
Posted by Arne Hartherz to makandra dev (2014-11-13 17:11)