patternjavascriptCritical
String.IsNullOrEmpty in JavaScript
Viewed 0 times
javascriptstringisnullorempty
Problem
I am aware of it being frowned upon to do something like write C# in JavaScript. (see this if you don't know what I'm talking about)
But as a judgement call, I think we could stand to have a relatively simple check for values that are
But as a judgement call, I think we could stand to have a relatively simple check for values that are
null or empty, so I'm looking for feedback on this implementation of String.isNullOrEmpty.String.isNullOrEmpty = function (value) {
return (!value || value == undefined || value == "" || value.length == 0);
}Solution
Starting with:
Looking at the last condition, if value == "", it's length MUST be 0. Therefore drop it:
But wait! In JS, an empty string is false. Therefore, drop
And
And we don't need parentheses:
Q.E.D.
return (!value || value == undefined || value == "" || value.length == 0);Looking at the last condition, if value == "", it's length MUST be 0. Therefore drop it:
return (!value || value == undefined || value == "");But wait! In JS, an empty string is false. Therefore, drop
value == "":return (!value || value == undefined);And
!undefined is true, so that check isn't needed. So we have:return (!value);And we don't need parentheses:
return !valueQ.E.D.
Code Snippets
return (!value || value == undefined || value == "" || value.length == 0);return (!value || value == undefined || value == "");return (!value || value == undefined);return (!value);return !valueContext
StackExchange Code Review Q#5572, answer score: 126
Revisions (0)
No revisions yet.