snippetjavascriptTip
How can I check for a blank value in JavaScript?
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'
First of all, any falsy values should be considered blank. These include
Secondly, empty arrays and objects should also be considered blank. This can be easily checked by using
In addition to the empty string (
Finally, we can check for some commonly-used built-in objects. Invalid
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); // trueSecondly, 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); // trueconst isEmptyCollection = value =>
(Array.isArray(value) || value === Object(value)) &&
!Object.keys(value).length;
isEmptyCollection([]); // true
isEmptyCollection({}); // trueconst isWhitespaceString = value =>
typeof value === 'string' && /^\s*$/.test(value);
isWhitespaceString(' '); // true
isWhitespaceString('\t\n\r'); // trueContext
From 30-seconds-of-code: blank-value
Revisions (0)
No revisions yet.