Is there a string.Empty
in JavaScript, or is it just a case of checking for ""
?
56 Answers
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against ""
using the ===
operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !==
operator:
if (strValue !== "") {
// strValue was not an empty string
}
-
286Testing the length property may actually be faster than testing the string against "", because the interpreter won't have to create a String object from the string literal. Commented Oct 1, 2008 at 20:07
-
82@Vincent doing some naïve profiling in Chrome developer tools, testing
=== ''
vs.length
didn't show any discernible improvement (and using.length
only works if you can assume that you have a string)– bdukesCommented Sep 27, 2010 at 13:19 -
48@bdukes when you start to care about that kind of micro-optimizations, I don't think Chrome is the browser where you are having most of your performance problems... Commented Sep 27, 2010 at 16:18
-
40Just to note, if your definition of "empty string" includes whitespace, then this solution is not appropriate. A string of 1 or more spaces returns true above. If you are using JQuery you can simply use this: if ($.trim(ref).length === 0) - as per this answer to a similar question: stackoverflow.com/questions/2031085/… Commented Oct 3, 2011 at 15:02
-
154
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length
attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined
in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String
prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
-
48
-
136@Vincent Conditions are often written like this
if (variable == constant value)
and if you forget an '=' then you're assigning the constant value to the variable instead of testing. The code will still work as you can assign variable in a if. So a safer way to write this condition is to reverse the constant value and the variable. This way when you test your code you'll see an error (Invalid lef-hand side in assignment). You can also use something like JSHint to disallow assignment in conditions and be warned when you write one. Commented Sep 23, 2013 at 9:58 -
12/^\s*$/.test(str) can be replaced with str.trim().length === 0 Commented Jun 19, 2015 at 12:35
-
51@Vincent this is also called "Yoda Conditions", like
if blue is the sky
. See dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html– AZ.Commented Jan 26, 2016 at 0:12 -
3It isn't really a good idea to be extending native prototypes though, it is generally considered a bad practice that a lot of people just recommend against doing so entirely as there are safer ways that are just as good. There is a SO discussion on the topic here, but every JS programming book I've read has strongly recommended against it. For OPs problem I usually just do
if (!str) { // i am sure str is empty null or undefined here if I'm sure it won't be another data type }
Commented Jan 8, 2020 at 18:55
All the previous answers are good, but this will be even better. Use dual NOT operators (!!
):
if (!!str) {
// Some code here
}
Or use type casting:
if (Boolean(str)) {
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str
is a variable.
It returns
false
fornull
,undefined
,0
,000
,""
,false
.It returns
true
for all string values other than the empty string (including strings like"0"
and" "
)
-
58Is there any difference between the behavior of
if(str)
andif(!!str)
? Commented Dec 19, 2014 at 18:28 -
7@PeterOlson if you are trying to save a variable as a boolean that checks multiple strings for content then you would want to do this.. aka
var any = (!!str1 && !!str2 && !!str3)
handling if there is a number in there as well Commented Mar 10, 2015 at 23:00 -
51This is the solution I always use.
!!str.trim()
to make sure the string is not made of whitespaces only. Commented Feb 11, 2016 at 10:56 -
29Not not looks like a hack,
Boolean(str)
is a lot more readable and less "wtfish".– shinzouCommented Oct 17, 2016 at 21:28 -
11This is simply useless in a
if
, it converts falsy values tofalse
and truthy values totrue
. Aif
block either executes or not based on wether the expression is truthy, there is no point adding!!
– Oli CrtCommented Sep 8, 2020 at 9:03
The closest thing you can get to str.Empty
(with the precondition that str is a String) is:
if (!str.length) { ...
-
27
-
8
-
1Note that strings aren't the only type of variable that have a
length
attribute. Arrays do as well.– FlimmCommented Aug 11, 2021 at 15:15
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
if(str.replace(/\s/g,"") == ""){
}
-
8But does the job if what you actually want to test for is a string with non-space content. Is there a less-expensive way to test this?– flashCommented Oct 22, 2010 at 10:02
-
4
-
30Instead of removing all the spaces, why not just check if there's a non-space? Has 2 advantages that it can bail out early if there is a non-space character, and it doesn't have return a new string which you then check against.
if(str.match(/\S/g)){}
– mpenCommented Jun 20, 2011 at 4:29 -
34@Mark FYI, you wouldn't need the global modifier, since the match of the first occurrence of a non-space character would mean the string is not empty:
str.match(/\S/)
– neezerCommented Jun 27, 2011 at 15:04 -
2Perhaps
/\S/.test(str)
is better thanstr.match(/\S/)
because it doesn't bother with returning an array of matched results (might be micro performance gain there). Also, when just testing a string against a regexp, use the RegExp.test()
method to better convey that intent. Commented Dec 7, 2016 at 20:19
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
-
6This solution is more language agnostic. The only JavaScript feature it relies on is typeof. So it is a good example of a solution you can use when you don't trust the implementations in different browsers and don't have time to grab a better solution. (IE, no internet access). It's something like a proof. Not the cleanest but you can be sure it will work without knowing too much about JavaScript. Commented Apr 20, 2012 at 13:11
-
2I'd go even a bit further, and nail it with a === operator for the undefined case. Otherwise it's just simply the perfect answer. Commented Jan 25, 2018 at 10:06
-
1The
typeof
in theswitch
did not work for me. I added aif (typeof e == "undefined")
test and that works. Why?– LucasCommented Apr 17, 2018 at 11:15 -
2
case typeof(e) == "undefined":
is wrong; that matches ane
offalse
, not ofundefined
. Apparently this was a suggested edit which got approved. The originalcase typeof this == "undefined":
still doesn’t make any sense. There’s also no reason to considerfalse
,0
, and"0"
“empty”. Commented Jul 2, 2021 at 0:54 -
2This function returns true for
isEmpty("0")
, which to me is surprising and unwanted behaviour. In Javascript,"0"
is evaluated to true in boolean contexts, and so I would not expect it to be considered empty.– FlimmCommented Aug 11, 2021 at 14:57
Performance
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
- the simple solutions based on
!str
,==
,===
andlength
are fast for all browsers (A,B,C,G,I,J) - the solutions based on the regular expression (
test
,replace
) andcharAt
are slowest for all browsers (H,L,M,P) - the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group
Details
In the below snippet I compare results of chosen 18 methods by use different input parameters
""
"a"
" "
- empty string, string with letter and string with space[]
{}
f
- array, object and function0
1
NaN
Infinity
- numberstrue
false
- Booleannull
undefined
Not all tested methods support all input cases.
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);
And then for all methods I perform speed test case str = ""
for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here
-
2Kind of misleading since it combines trim solutions with no-trim solutions.– seanCommented Dec 4, 2020 at 9:47
You can use lodash: _.isEmpty(value).
It covers a lot of cases like {}
, ''
, null
, undefined
, etc.
But it always returns true
for Number
type of JavaScript primitive data types like _.isEmpty(10)
or _.isEmpty(Number.MAX_VALUE)
both returns true
.
-
-
3@Erich Because
" "
is not empty._.isEmpty("");
returns true.– MoshiCommented Mar 25, 2020 at 7:34 -
1quite true - i mentioned this because a few of the other answers on here imply form validation and checking if a string consists of only whitespace, and this single lodash function by itself will not solve that problem.– ErichCommented Mar 26, 2020 at 0:30
Very generic "All-In-One" Function (not recommended though):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
-
3
-
4-1 They are testing for different things. It makes no sense to put them all into one
if
statement. Commented Apr 1, 2014 at 22:39 -
2typeof MyVariable == 'undefined' doesn't discern between an initialized variable with an undefined value and an undeclared variable unless the variable was initially declared and initialized to null. Checking the length property causes the string primitive to be wrapped in a string object. Commented Jan 28, 2016 at 21:57
var s; // undefined
var s = ""; // ""
s.length // 0
There's nothing representing an empty string in JavaScript. Do a check against either length
(if you know that the var will always be a string) or against ""
-
I don't understand this sentence:
There's nothing representing an empty string in JavaScript.
. What about""
, doesn't that represent an empty string?– FlimmCommented Aug 11, 2021 at 15:17
Try:
if (str && str.trim().length) {
//...
}
-
str.trim().length
will do faster thanstr.trim()
, by around 1% according to my own testing result. Commented Mar 6, 2019 at 6:32 -
OP is looking to test for empty string, undefined, or null. This is testing for a string that is not any of those conditions. He didn't say anything about whitespace only strings either. You can test for OP's conditions with just this, as long as you are sure no other data types are stored in the variable:
if (!str) { ... }
Commented Jan 8, 2020 at 19:10
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == ""
.
As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
-
13Bad idea. You'll get true if strVar is accidentally assigned 0. Commented Sep 30, 2008 at 19:21
-
5I agree that making your intention clear is more important than any micro-optimizations other methods might yield, but using the strict comparison operator
===
would be better. It only returns true ifstrVar
is an empty string. Commented Jun 13, 2015 at 17:52 -
-
4@ValentinHeinitz if str were assigned a falsey value of 0 or "0", if(str) would falsely report true. The best approach is if(str === ""). It's simple and it will never fail. Commented Jan 28, 2016 at 22:02
-
1Which equals operator (== vs ===) should be used in JavaScript comparisons? Commented Jan 18, 2018 at 21:19
There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.
null
, undefined
, and ""
are all falsy.
When evaluating an empty string, it's often because you need to replace it with something else.
In this case, you can expect the following behavior.
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
With that in mind, a method or function that can return whether or not a string is ""
, null
, or undefined
(an invalid string) versus a valid string is as simple as this:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
Please note, you probably also want to trim()
the string since "" !== " "
.
-
thank you, i like your anwser, it is so simple. So just use: if (str) { //some code } when str is not null && not undefined && not empty string, then the if condition is true– Zi SangCommented Aug 1, 2023 at 19:19
-
Yes, you can do that. You will probably, however, want to ensure that there's not empty white space. Because:
js const emptStr = ""
Is not the same asjs const notEmptyStr = " "
And the latter is not falsy.– trn450Commented Dec 5, 2023 at 17:22
if ((input?.trim()?.length || 0) > 0) {
// input must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Or in function form:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Explanation:
If input
is undefined
or null
then the null coalescing ?.
will result in input?.trim()?.length
will be undefined
or null
. ORing (||
) that with 0
will give 0
. 0
is not > 0
therefore the result will be false
, ie it IS a nil value.
If input
is empty or whitespace then .trim()
will remove leading and ending whitespace, which will keep an empty input the same, and convert any whitespace to an empty value. The length of an empty string is then 0
, and as above, 0
is not > 0
, therefore the result will be false
, ie it IS empty or only whitespace.
If input
is any other string, it's length will be > 0 after calling .trim()
, and therefore the result will be true
, ie it IS NOT a nil value, and it IS NOT empty or only whitespace.
-
2
-
-
why so complicated? how about
const isNilOrWhitespace = input => !input?.trim();
– ThomasCommented Jun 30, 2023 at 20:45
A lot of answers, and a lot of different possibilities!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
However, as many other examples are available. The best functional method to go about this, I would suggest:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
return true;
else
return false;
}
A bit excessive, I know.
-
2Checking for undefined would need to be moved to first in the checks, or undefined items will throw exceptions on the earlier checks. Commented Jun 16, 2016 at 14:10
-
-
str.length === 0
returns true for any function that has no formal parameters.– RobGCommented Oct 16, 2019 at 12:52 -
str.length === 0 || str === "" both would do the same task. Commented Nov 3, 2020 at 12:06
check that
var a;
existtrim out the false spaces in the value, then test for emptiness
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
-
The string
" "
is not empty, but it would be considered empty by this condition.– FlimmCommented Aug 11, 2021 at 15:18
You could also go with regular expressions:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
-
1It works, but it's also horribly expensive ops-wise. Good if you just want to check one or two things, not a large set.– OrpheusCommented May 11, 2015 at 16:38
I usually use something like this,
if (!str.length) {
// Do something
}
-
4Fastest if you know that the variable is a string. Throws an error if the variable is undefined. Commented Feb 20, 2014 at 10:16
-
@AdrianHope-Bailie why would you test an undefined variable? Commented Apr 1, 2014 at 0:18
-
3@AbimaelMartell Why not? You have a variable that either you declared or that was passed to you from some scope you have no control over such as in a response from a method or API call. You can assume it contains a value and use the check above but if it is not defined or is null you will get an error. var test = null; if(!test.length){alert("adrian is wrong");} Commented Apr 1, 2014 at 8:28
-
OP was asking for "how to check for an empty string", un undefined variable is not an empty string. Anyway you could check
typeof variable != "undefined"
before checking if is empty. Commented Apr 1, 2014 at 18:56
Also, in case you consider a whitespace filled string as "empty".
You can test it with this regular expression:
!/\S/.test(string); // Returns true if blank.
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JavaScript, 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 !value
-
what happens if
value = false
orvalue = 0
. will you return the correct response according to the question?– nerezCommented Apr 28, 2020 at 4:15
I use a combination, and the fastest checks are first.
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
-
3Just wondering if you could explain when the length check would be necessary? Wouldn't !pString catch anything that was null/empty string? This seems to work. var test=''; if (!test) alert('empty');– NicholiCommented Oct 27, 2011 at 21:49
-
2I didn't see this comment until a decade later. But yes, you're right, I'll update. :)– WillCommented Jul 5, 2021 at 15:06
-
1
-
I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
To test its nullness one could do something like this:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).
-
2Interesting analysis. I don't think this would be relevant in 99.9% of cases. BUT I recently found that MySQL evaluates a column to "null" if (and only if) that column contains the null character ("\0"). Oracle on the other hand would not evaluate "\0" as being null, preferring to treat it as a string of length 1 (where that one character is the null character). This could cause confusion if not dealt with properly, because many web-developers do work with a back-end database, which might pass through different types of "null" values. It should be at the back of every developer's mind. Commented Oct 20, 2012 at 12:20
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value)
since if you check 0
it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
-
Probably better use Boolean(value) construct that treats undefined and null values (and also 0, -0, false, NaN) as false. See stackoverflow.com/questions/856324/… Commented Nov 29, 2019 at 14:34
Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, []. So I just wrote this.
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
Use cases and results.
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
-
If you simply stop using == and use ===, then this solves the problem if(s === ""). Commented Jan 28, 2016 at 22:05
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).
My version:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
-
2Huh? If you are expecting a string,
empty(0)
andempty(7)
should return the same value. Commented Apr 1, 2014 at 22:44 -
In my particular case -
empty("0")
must returnfalse
(because that is a not empty string), butempty(0)
must returntrue
because it is empty :)– AndronCommented Apr 2, 2014 at 11:24 -
But 0 isn't empty! It's a number, and numbers can't be full or empty. Of course, it's your function and so must satisfy your requirements, but
empty
is a misleading name in this case. Commented Apr 2, 2014 at 21:15 -
-
As I say, it's your function: call it what you want. But
empty
is an inaccurate and misleading name. It's interesting that PHP also has a poorly-namedempty
function, but PHP's failings don't have anything to do with JavaScript. Commented Apr 3, 2014 at 22:57
Trimming whitespace with the null-coalescing operator:
if (!str?.trim()) {
// do something...
}
-
It looks cool but str.trim() is sufficient. One should never overcomplicate things IMO.– HexodusCommented Feb 23, 2021 at 15:16
-
2Just throwing it out for those people who might need it.
?.
couldn't be less complicated..trim()
would throw an error ifstr
is nullish.– seanCommented Feb 24, 2021 at 10:48
There's no isEmpty()
method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test
is undefined
or null
.
-
I'm pretty sure
test === ""
is equivalent, and it's shorter.– FlimmCommented Aug 11, 2021 at 15:21
null
orundefined
empty? An empty string is an empty string, it is notnull
orundefined