HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I check for a blank value in JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptcheckhowvaluecanblankfor

Problem

JavaScript doesn't have a built-in way to check if a value is blank, but it's easy to create one. Before we do, however, we should define the behavior of such a method. The inspiration for this comes from Rails' blank? method, but modified to fit JavaScript's needs.
First of all, any falsy values should be considered blank. These include null, undefined, 0, false, '', and NaN.
Secondly, empty arrays and objects should also be considered blank. This can be easily checked by using Object.keys() for both types of values.
In addition to the empty string (''), whitespace-only strings should be considered blank, too. A regular expression can be used to check for this.
Finally, we can check for some commonly-used built-in objects. Invalid Date instances, as well as empty Set and Map instances should all be considered blank.

Solution

const isFalsy = value => !value;

isFalsy(null); // true
isFalsy(undefined); // true
isFalsy(0); // true
isFalsy(false); // true
isFalsy(''); // true
isFalsy(NaN); // true


Secondly, empty arrays and objects should also be considered blank. This can be easily checked by using Object.keys() for both types of values.
In addition to the empty string (''), whitespace-only strings should be considered blank, too. A regular expression can be used to check for this.
Finally, we can check for some commonly-used built-in objects. Invalid Date instances, as well as empty Set and Map instances should all be considered blank.
Putting everything together, we can finally set up our isBlank method.

Code Snippets

const isFalsy = value => !value;

isFalsy(null); // true
isFalsy(undefined); // true
isFalsy(0); // true
isFalsy(false); // true
isFalsy(''); // true
isFalsy(NaN); // true
const isEmptyCollection = value =>
  (Array.isArray(value) || value === Object(value)) &&
  !Object.keys(value).length;

isEmptyCollection([]); // true
isEmptyCollection({}); // true
const isWhitespaceString = value =>
  typeof value === 'string' && /^\s*$/.test(value);

isWhitespaceString(' '); // true
isWhitespaceString('\t\n\r'); // true

Context

From 30-seconds-of-code: blank-value

Revisions (0)

No revisions yet.