How do I check for an empty/undefined/null string in JavaScript?
Asked Answered
U

55

4016

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?

Urquhart answered 30/9, 2008 at 17:17 Comment(7)
just FYI, i think the most useful APIs for the String class are at Mozilla and javascript kit. [elated.com](elated.com/articles/working-with-strings ) has a tutorial on all of String's properties, methods,... Please note: the Mozilla link has been updated to developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…Ellipsoid
Check this one : https://mcmap.net/q/24549/-js-how-to-check-empty-string-and-space-duplicateSubsist
It would help greatly if the requirement was clearly specified. For what values should isEmpty return true? Checking for "" infers that it should only return true if the value is Type string and length 0. Many answers here assume it should also return true for some or all falsey values.Sepia
str.length > -1Staffman
I completely agree with @RobG, this question is badly defined. Why on earth would you consider null or undefined empty? An empty string is an empty string, it is not null or undefinedBeauvoir
Also, an empty string cannot contain whitespace, like a lot of answers are assuming!Beauvoir
@GeneT's link is broken, so here's an updated link to Mozilla's reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Cherri
M
4958

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
}
Minette answered 30/9, 2008 at 17:20 Comment(13)
Testing 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.Deictic
@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)Minette
@Minette 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...Deictic
Just 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: #2031585Raddie
As expected .length > 0 is actually much faster than comparing to a string literal! Check out this jsPerfAnatole
@Chad, Your jsPerf is quite flawed, as one of the tests compares for a specific value, whereas the other compares for any value except empty. So to make it fair the first test should be s!=="" which is 'only' 24% slower than s.length > 0Skinner
Since it varies from each version of Chrome the proper way is to write it so that it identifies which version of chrome is in which list and uses the fastest method :P You'll spend more cycles checking out which version of chrome you're running and which is the fastest. Honestly it's so close in comparison lately just pick whatever flavor suits you best. Not checking the length is nice for some duck-type-ability. Although everyone knows the dangers of ducks and should be running TypeScript; fact™.Loquat
str=0; if(str) retun falseDreadfully
what if we need to pass this check as lamda? f.e: if (users.some(u => u.GroupRole)){} In this case there's complilation error telling me to pass bool not stringTraynor
@kir.gera, JavaScript doesn't give compilation errors, are you getting this error from the TypeScript compiler? If your compiler wants a strict bool value, you could to Boolean(u.GroupRole) or !!u.GroupRoleMinette
@Urquhart This is not Good answer because in some situation at start create page initializing by null and this strValue === "" not work. the best syntax is !strValue GoodLuckOsugi
Before your focus going to performance difference, think about how many times will it be run. For example the "if" statement runned once per site, your performance optimalisation is near zero. and if your code is longer than original, mybe you loose more time on network than won on javascript execution. And at last, when you use any build tool, then these microoptimalization will be lost. So my advice is "write more readable code"Veiling
Surprised not to see any mention of "falsy values" here...Dentiform
G
1425

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.

Geraint answered 16/7, 2010 at 1:45 Comment(14)
why 0 === str.length instead of str.length === 0 ?Pedropedrotti
@Pedropedrotti 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.Landeros
I forgot to mention that as you mostly use '===' or '!==' you are less exposed to that kind of mistake.Landeros
shame that /^\s*$/.test(str) is not really readable - maybe removing spaces using simpler code or regex would be better? see #6623731 and also #10800855Libelous
I like that, and I added this to the String prototype String.prototype.isEmpty = function () { return (!this || 0 === this.length); };Furred
/^\s*$/.test(str) can be replaced with str.trim().length === 0Herculean
@Pedropedrotti this is also called "Yoda Conditions", like if blue is the sky. See dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.htmlKeslie
How is return (this.length === 0 || !this.trim()) any better than just return !this.trim()?Brae
It 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 }Slickenside
Empty strings are falsey, so there's the second part of the condition isn't really needed: (! str || str.length == 0)Beauvoir
This is the best answer and handles every scenario I can test against it! (the isBlank() one)Pater
@Jano Why the need for checking length here: return (!str || str.length === 0 )?Ardussi
@ruffin Arrays. console.log([] ? "true" : "false") prints "true".Need
@JustinC Truthy, no doubt no doubt. I'm not sure what I was thinking before -- I would say I was only worried about strings. That is, in TypeScript, if str is of type string, you would not need the .length check. But I also said, "another object type with .length", which I assume meant I was thinking of non-strings (which makes sense in dynamic-JavaScript-land), in which case arrays are the obvious answer. So who knows what I was thinking. But now I'm thinking I'll just delete that comment. 😕😖 Though an empty array is not falsy -- what are we trying to check for again? 😉🤷Assiduity
B
559

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 for null, undefined, 0, 000, "", false.

  • It returns true for all string values other than the empty string (including strings like "0" and " ")

Beeline answered 30/3, 2011 at 13:34 Comment(15)
Is there any difference between the behavior of if(str) and if(!!str)?Mervin
@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 wellThereunder
This is the solution I always use. !!str.trim() to make sure the string is not made of whitespaces only.Escadrille
Not not looks like a hack, Boolean(str) is a lot more readable and less "wtfish".Zellers
Note that !! is not an operator. It is one operator applied twice.Chiliasm
@JohnRuddell aren't the bangs redundant in var any = (!!str1 && !!str2 && !!str3)? Won't the && operator convert the operands to booleans anyway?Nihilism
@arth you can do that, it depends on your code style. When I do a Boolean check I like to cast to a bool via !! so you ensure consistent behavior... when you aren't dealing with Boolean values, a browsers implementation could potentially behave differentlyThereunder
@JohnRuddell Why would a browser's implicit conversion of a variable to a Boolean vary between the ! operator and the && operator? .. and if it would, why trust one and not the other?Nihilism
@Nihilism @JohnRuddell: no, the bangs aren't redundant. For example, 'aa' && 'ddd' returns 'ddd', not true. 'ddd' happens to further evaluate as true, which is why you can use just 'aa' && 'ddd' as-is in an if statement. But if you're assigning the result to a boolean the bangs are needed.Gennie
@JohnRuddell @Arth: in other words, javascript's && does not return a boolean unless the operand it picks happens to be a boolean. Here's the definition of its behavior (for expr1 && expr2): "If expr1 can be converted to true, returns expr2; else, returns expr1".Gennie
@AlvinThompson Ah yes, I missed that.. thanks, good point! When assigning a boolean var, explicit conversion is necessary, but could be done as !!(str1 && str2 && str3) or Boolean(str1 && str2 && str3) instead. When not assigning, an explicit conversion is superfluous, if (str1 && str2 && str3){}is enough..Nihilism
This is simply useless in a if, it converts falsy values to false and truthy values to true. A if block either executes or not based on wether the expression is truthy, there is no point adding !!Menhir
For those wondering: 1. Boolean(expr) is just the same as !!expr 2. Boolean(expr) inside an if is sort of useless; if already implicitly casts the expression given inside it. This might come as a surprise to those coming from C# for example.Limburg
This doesnt work with string whitespace. Adding Darias suggestion doesnt work on nulls.Pater
Unless you're interfacing with a JavaScript-hostile third party library (including JSX!), no, please leave off the !! -- here's why. JavaScript a dynamic language, and it'll pay off for you in the long run to think like the language, not coerce the language to think like you. What this answer is really telling us is that if (str) { /* go */ } else { /* don't go */ } is all the check you need.Assiduity
E
134

The closest thing you can get to str.Empty (with the precondition that str is a String) is:

if (!str.length) { ...
Eleen answered 30/9, 2008 at 19:17 Comment(3)
Wouldn't that throw an exception is str is null?Indaba
@PicMickael Yes! So would str.Empty.Eleen
Note that strings aren't the only type of variable that have a length attribute. Arrays do as well.Beauvoir
A
116

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,"") == ""){
}
Agglutinogen answered 30/9, 2008 at 23:8 Comment(8)
But 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?Gules
How about the length property?Abatis
Instead 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)){}Micropyle
@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/)Pastiche
why it is expensive? If truly is, then why jQuery uses this method? You can find this in jQuery's source var trimLeft = /^\s+/, trimRight = /\s+$/;Lanyard
+1 I tried this method and it worked for me. The user may enter blank spaces which is still blank.Euphonize
if(str.replace(/^\s+|\s+$/g,"")){...}+ would be enoughCharioteer
Perhaps /\S/.test(str) is better than str.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.Eleen
Z
78

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
Zebra answered 9/7, 2010 at 18:52 Comment(10)
This 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.Nerin
I'd go even a bit further, and nail it with a === operator for the undefined case. Otherwise it's just simply the perfect answer.Punic
The typeof in the switch did not work for me. I added a if (typeof e == "undefined") test and that works. Why?Asturias
@Asturias Because this was a typo or an oversight. Your modification is the correct approach. (the original refers to the context of the empty function, not the e parameter, which is what the function is supposed to check)Snack
Could we use case undefined: instead of case typeof(e) == "undefined":?Stressful
case typeof(e) == "undefined": is wrong; that matches an e of false, not of undefined. Apparently this was a suggested edit which got approved. The original case typeof this == "undefined": still doesn’t make any sense. There’s also no reason to consider false, 0, and "0" “empty”.Ettore
Just goes to show how ludicrous this beautiful language is :(Avowal
This 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.Beauvoir
@BorisJ. yes, using case undefined: would be a correct fix for this bug. (I edited the answer to use this instead).Femur
This solution is as bad as loose equality (with how it treats '0' as "empty"), and it's incomplete (it won't check if a set, map, or user-defined class is empty if those got passed in), and it really doesn't make much sense (Why are we checking for emptiness on numbers and booleans? Those aren't containers). And, it's unnecessary - you should know what data type you're dealing with, and be able to do the appropriate emptiness check for it on-the-spot. This will be much cleaner and simpler.Femur
F
74

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,==,=== and length are fast for all browsers (A,B,C,G,I,J)
  • the solutions based on the regular expression (test,replace) and charAt 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

Enter image description here

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 function
  • 0 1 NaN Infinity - numbers
  • true false - Boolean
  • null 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

Enter image description here

Fourfold answered 31/12, 2019 at 18:48 Comment(1)
Kind of misleading since it combines trim solutions with no-trim solutions.Limburg
A
61

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.

Atomics answered 17/8, 2017 at 6:51 Comment(3)
_.isEmpty(" "); // => falseButtermilk
@Buttermilk Because " " is not empty. _.isEmpty(""); returns true.Atomics
quite 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.Buttermilk
F
43

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.

Fite answered 27/2, 2014 at 20:31 Comment(3)
Any chance you could explain what each check is doing? :)Akin
-1 They are testing for different things. It makes no sense to put them all into one if statement.Thromboplastic
typeof 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.Heavierthanair
S
42
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 ""

Stephenstephenie answered 30/9, 2008 at 17:42 Comment(1)
I don't understand this sentence: There's nothing representing an empty string in JavaScript. . What about "", doesn't that represent an empty string?Beauvoir
K
41

Try:

if (str && str.trim().length) {  
    //...
}
Kisumu answered 9/1, 2013 at 2:54 Comment(2)
str.trim().length will do faster than str.trim(), by around 1% according to my own testing result.Honest
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) { ... }Slickenside
S
32

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.

Sufism answered 30/9, 2008 at 17:20 Comment(5)
Bad idea. You'll get true if strVar is accidentally assigned 0.Frulla
I 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 if strVar is an empty string.Cheekpiece
The check fails if undefined. So if(str) works betterFurnishing
@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.Heavierthanair
Which equals operator (== vs ===) should be used in JavaScript comparisons?Kwangchow
H
25
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.

Hysteria answered 24/8, 2020 at 9:55 Comment(3)
could you please give more explanation?Remington
Explanation addedHysteria
why so complicated? how about const isNilOrWhitespace = input => !input?.trim();Honeycomb
D
24

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 "" !== " ".

Debonair answered 5/11, 2020 at 19:24 Comment(2)
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 trueSinfonietta
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 as js const notEmptyStr = " " And the latter is not falsy.Debonair
C
22

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.

Cashbox answered 31/3, 2016 at 8:29 Comment(4)
Checking for undefined would need to be moved to first in the checks, or undefined items will throw exceptions on the earlier checks.Ref
Completely agree! NICE CATCH. I will edit my above answer!Cashbox
str.length === 0 returns true for any function that has no formal parameters.Sepia
str.length === 0 || str === "" both would do the same task.Tobit
M
21

You could also go with regular expressions:

if((/^\s*$/).test(str)) { }

Checks for strings that are either empty or filled with whitespace.

Measure answered 31/5, 2010 at 14:57 Comment(1)
It works, but it's also horribly expensive ops-wise. Good if you just want to check one or two things, not a large set.Crazy
R
21
  1. check that var a; exist

  2. trim out the false spaces in the value, then test for emptiness

     if ((a)&&(a.trim()!=''))
     {
       // if variable a is not empty do this 
     }
    
Reprint answered 24/2, 2015 at 15:38 Comment(1)
The string " " is not empty, but it would be considered empty by this condition.Beauvoir
L
20

I usually use something like this,

if (!str.length) {
    // Do something
}
Lettyletup answered 9/8, 2013 at 10:10 Comment(4)
Fastest if you know that the variable is a string. Throws an error if the variable is undefined.Metrist
@AdrianHope-Bailie why would you test an undefined variable?Morphophonemics
@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");}Metrist
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.Morphophonemics
B
18

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.
Burrows answered 15/5, 2013 at 14:55 Comment(0)
I
16

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());    
}
Increate answered 1/10, 2014 at 6:55 Comment(0)
S
14

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);
}
Subjoin answered 1/6, 2011 at 15:40 Comment(4)
Just 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');Redbird
I didn't see this comment until a decade later. But yes, you're right, I'll update. :)Subjoin
Combining our knowledge 1 decade at a time :)Redbird
@Redbird see you in 2031!Subjoin
S
14

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
Steward answered 10/2, 2020 at 8:34 Comment(1)
what happens if value = false or value = 0. will you return the correct response according to the question?Griff
S
13

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.).

Slush answered 31/7, 2012 at 14:5 Comment(1)
Interesting 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.Euhemerus
L
11

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; } }]
];
Limitless answered 14/5, 2013 at 10:18 Comment(1)
If you simply stop using == and use ===, then this solves the problem if(s === "").Heavierthanair
C
11

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
Cuprite answered 12/3, 2018 at 8:48 Comment(0)
T
11

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

Triggerfish answered 23/10, 2019 at 21:13 Comment(1)
Probably better use Boolean(value) construct that treats undefined and null values (and also 0, -0, false, NaN) as false. See #856824Too
H
10

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.

Hydrogeology answered 8/5, 2013 at 17:15 Comment(5)
Huh? If you are expecting a string, empty(0) and empty(7) should return the same value.Thromboplastic
In my particular case - empty("0") must return false (because that is a not empty string), but empty(0) must return true because it is empty :)Hydrogeology
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.Thromboplastic
I think that name empty is good. In php docs for empty function: Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE. The difference between PHP and this function - that string '0' will be not identified as empty.Hydrogeology
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-named empty function, but PHP's failings don't have anything to do with JavaScript.Thromboplastic
G
10

Try this:

export const isEmpty = string => (!string || !string.length);
Gothar answered 10/5, 2019 at 21:33 Comment(0)
L
10

Trimming whitespace with the null-coalescing operator:

if (!str?.trim()) {
  // do something...
}
Limburg answered 4/12, 2020 at 9:55 Comment(2)
It looks cool but str.trim() is sufficient. One should never overcomplicate things IMO.Allene
Just throwing it out for those people who might need it. ?. couldn't be less complicated. .trim() would throw an error if str is nullish.Limburg
M
9

Ignoring whitespace strings, you could use this to check for null, empty and undefined:

var obj = {};
(!!obj.str) // Returns false

obj.str = "";
(!!obj.str) // Returns false

obj.str = null;
(!!obj.str) // Returns false

It is concise and it works for undefined properties, although it's not the most readable.

Manager answered 19/7, 2012 at 2:0 Comment(1)
You are checking for truthiness, here, which is bit more complicated than merely checking for empty strings, undefined or nullBeauvoir
D
9

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.

Doubletongue answered 4/11, 2016 at 22:28 Comment(1)
I'm pretty sure test === "" is equivalent, and it's shorter.Beauvoir
C
7

I usually use something like:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}
Cyclostome answered 15/2, 2010 at 2:46 Comment(1)
== operator is not strict. So if str == "", str can be null, undefined, false, 0, [], etc..Latterly
S
7

Try this

str.value.length == 0
Splendent answered 22/7, 2010 at 15:30 Comment(2)
"".value.length will cause an error. It should be str.length === 0Grant
This trow a TypeError If str is equal to undefined or nullLatterly
G
7

You can easily add it to native String object in JavaScript and reuse it over and over...
Something simple like below code can do the job for you if you want to check '' empty strings:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

and you can call it this way:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
Gemagemara answered 7/10, 2017 at 2:33 Comment(3)
What benefit is there to doing !(!!this.length) rather than just !this (or !this.trim() for the second option)? A zero-length string is falsy already, the parentheses are redundant, and negating it three times is exactly the same as negating it once.Gossipry
Please don't pollute prototypes.Limburg
It's generally considered bad practise to use monkey-patching like this.Beauvoir
B
6

Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.

The thing is: think carefully about what your app must do and can accept. Build something robust.

If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.

As an example of something that will explode if you follow some advices here not carefully.


var getLastChar = function (str) {
 if (str.length > 0)
   return str.charAt(str.length - 1)
}

getLastChar('hello')
=> "o"

getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'

So, I'd stick with


if (myVar === '')
  ...

Bitch answered 15/7, 2013 at 10:55 Comment(1)
This answer should be pinned to the top.Beauvoir
L
6

Check if it's type string AND if it's not empty:

const isNonEmptyString = (val) => typeof val === 'string' && !!val
Lieselotteliestal answered 6/12, 2022 at 17:53 Comment(0)
P
5

You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:

    let undefinedStr;
    if (!undefinedStr) {
      console.log("String is undefined");
    }
    
    let emptyStr = "";
    if (!emptyStr) {
      console.log("String is empty");
    }
    
    let nullStr = null;
    if (!nullStr) {
      console.log("String is null");
    }
Pupiparous answered 6/5, 2014 at 6:38 Comment(1)
The first condition works for any falsey value, not just undefined. This answer is not checking for type.Beauvoir
T
5

You can able to validate following ways and understand the difference.

var j = undefined;
console.log((typeof j == 'undefined') ? "true":"false");
var j = null; 
console.log((j == null) ? "true":"false");
var j = "";
console.log((!j) ? "true":"false");
var j = "Hi";
console.log((!j) ? "true":"false");
Tying answered 30/11, 2017 at 6:26 Comment(0)
P
5

You can check this using the typeof operator along with the length method.

const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
Psilomelane answered 14/1, 2021 at 17:4 Comment(0)
T
5

Try this code:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}
Tongs answered 8/10, 2021 at 7:56 Comment(1)
What is the purpose of (strValue.trim()).length === 0) at the end of the condition? Isn't it redundant with strValue.trim() === ""?Ethelda
F
4
function tell()
{
    var pass = document.getElementById('pasword').value;
    var plen = pass.length;

    // Now you can check if your string is empty as like
    if(plen==0)
    {
        alert('empty');
    }
    else
    {
        alert('you entered something');
    }
}

<input type='text' id='pasword' />

This is also a generic way to check if field is empty.

Fears answered 6/8, 2010 at 16:28 Comment(0)
E
4

I prefer to use not blank test instead of blank

function isNotBlank(str) {
   return (str && /^\s*$/.test(str));
}
Eaglewood answered 3/7, 2013 at 4:16 Comment(3)
Putting negation into function names is a bad idea. You code itself is fine,but the function should be called something like hasValue(). Why? What happens when you see code like this: "if (!isNotBlank(str))"... It is not immediately clear what the intent is supposed to be. It may not seem relevant to you for this simple example, but adding negation to a function name is always a bad idea.Diarmid
IsNotBlank is a standard function and very popular function in StringUtils commons.apache.org/proper/commons-lang/apidocs/org/apache/…Eaglewood
it also provides the IsBlank to avoid the double negatives. I believe function names should reflect the functionality they perform and it would be easier for developers to see understand when they see isBlank and IsNotBlank function in same class.Eaglewood
C
4

The Underscore.js JavaScript library, http://underscorejs.org/, provides a very useful _.isEmpty() function for checking for empty strings and other empty objects.

Reference: http://underscorejs.org/#isEmpty

isEmpty _.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

_.isEmpty([1, 2, 3]);
=> false

_.isEmpty({});
=> true

Other very useful Underscore.js functions include:

Cuirbouilli answered 10/6, 2015 at 8:44 Comment(0)
E
4

The following regular expression is another solution, that can be used for null, empty or undefined string.

(/(null|undefined|^$)/).test(null)

I added this solution, because it can be extended further to check empty or some value like as follow. The following regular expression is checking either string can be empty null undefined or it has integers only.

(/(null|undefined|^$|^\d+$)/).test()
Eanes answered 18/10, 2019 at 9:2 Comment(1)
A major flaw: this regex matches the string literal "null". (/(null|undefined|^$)/).test("null")Limburg
E
4

The ultimate and shortest variant of the isBlank function:

/**
 * Will return:
 * False for: for all strings with chars
 * True for: false, null, undefined, 0, 0.0, "", " ".
 *
 * @param str
 * @returns {boolean}
 */
function isBlank(str){
    return (!!!str || /^\s*$/.test(str));
}

// tests
console.log("isBlank TRUE variants:");
console.log(isBlank(false));
console.log(isBlank(undefined));
console.log(isBlank(null));
console.log(isBlank(0));
console.log(isBlank(0.0));
console.log(isBlank(""));
console.log(isBlank(" "));

console.log("isBlank FALSE variants:");
console.log(isBlank("0"));
console.log(isBlank("0.0"));
console.log(isBlank(" 0"));
console.log(isBlank("0 "));
console.log(isBlank("Test string"));
console.log(isBlank("true"));
console.log(isBlank("false"));
console.log(isBlank("null"));
console.log(isBlank("undefined"));
Egwan answered 22/8, 2021 at 10:12 Comment(0)
A
4

This is a falsy value.

The first solution:

const str = "";
return str || "Hello"

The second solution:

const str = "";
return (!!str) || "Hello"; // !!str is Boolean

The third solution:

const str = "";
return (+str) || "Hello"; // !!str is Boolean
Annamarieannamese answered 13/10, 2021 at 18:13 Comment(1)
The third solution is basically wrong when input is not a number, so that parsing result will be NaN which is also falsy.Honest
M
3

It's a good idea too to check that you are not trying to pass an undefined term.

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

I usually run into the case where I want to do something when a string attribute for an object instance is not empty. Which is fine, except that attribute is not always present.

Matriarchy answered 18/12, 2012 at 22:31 Comment(0)
S
2

An alternative way, but I believe bdukes's answer is best.

var myString = 'hello'; 
if(myString.charAt(0)){
    alert('no empty');
}
alert('empty');
Sedlik answered 10/2, 2013 at 10:20 Comment(0)
H
2

Using core (read vanilla) javascript we can leverage Object.is() for strict equality comparison. Following is a code snippet.

function validateString(arg) {
 if (Object.is(arg, "") || Object.is(arg, null) || Object.is(arg, undefined)) {
      return false;
 }
 return true;
}

Here is the JavaScript spec: https://262.ecma-international.org/12.0/#sec-object.is

Here is the Mozilla Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is

Hope this helps.

Harlequin answered 15/3, 2023 at 18:6 Comment(0)
S
0

Here are some custom functions I use for handling this. Along with examples of how the code runs.

const v1 = 0
const v2 = '4'
const v2e = undefined
const v2e2 = null
const v3 = [1, 2, 3, 4]
const v3e = []
const v4 = true
const v4e = false
const v5 = {
  test: 'value'
}
const v5e = {}
const v6 = 'NotEmpty'
const v6e = ''

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}

function isEmpty(v, zeroIsEmpty = false) {
  /**
   * When doing a typeof check, null will always return "object" so we filter that out first
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
   */
  if (v === null) {
    return true
  }

  if (v === true) {
    return false
  }

  if (typeof v === 'object') {
    return !Object.keys(v).length
  }

  if (isNumeric(v)) {
    return zeroIsEmpty ? parseFloat(v) === 0 : false
  }

  return !v || !v.length || v.length < 1
}

console.log(isEmpty(v1), isEmpty(v1, true))
console.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e))
console.log(isEmpty(v3), isEmpty(v3e))
console.log(isEmpty(v4), isEmpty(v4e))
console.log(isEmpty(v5), isEmpty(v5e))
console.log(isEmpty(v6), isEmpty(v6e))

Also for reference, here's the source for Lodash isEmpty:

Scheller answered 9/11, 2021 at 21:4 Comment(0)
C
0

complete example. use Object.keys() for types string,array, and object

function isEmpty(input){
    switch(typeof input){
      case 'undefined': return true
      case 'string':
      case 'object':
         return Object.keys(input).length == 0
      case 'boolean':
      case 'bigint':
      case 'number': return input == 0
    }
}
function log(...logs){
   for(let i = 0;i < logs.length;i++){
     if(i % 2 == 1){
        console.log(logs[i - 1],'=', logs[i])
     }
   }
}
log(
   isEmpty(),      'empty undefined',   // true
   isEmpty(''),    'empty string',      // true
   isEmpty('abc'), 'empty string',      // false
   isEmpty([]),    'empty array',       // true
   isEmpty([2,3]), 'empty array',       // false
   isEmpty({}),    'empty object',      // true
   isEmpty({a: 'abc'}), 'empty object', // false
   isEmpty(false), 'empty boolean',     // true
   isEmpty(true),  'empty boolean',     // false
   isEmpty(0n),    'empty bigint',      // true
   isEmpty(2n),    'empty bigint',      // false
   isEmpty(0),     'empty number',      // true
   isEmpty(2),     'empty number'       // false
)
Conductivity answered 11/5, 2023 at 15:57 Comment(0)
F
0

I use such approach

[null, undefined, ''].includes(value)
Finable answered 18/3 at 7:51 Comment(0)
U
-1
var x ="  ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
    alert("ya it is blank")
}
Unspoiled answered 8/4, 2014 at 9:37 Comment(0)
N
-2

Well, the simplest function to check this is...

const checkEmpty = string => (string.trim() === "") || !string.trim();

Usage:

checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.

It's that dead simple. :)

Nuts answered 4/7, 2021 at 6:16 Comment(2)
This will return true, even for strings that aren't empty that contain whitespace, such as " "Beauvoir
I agree, but most of the time you do need to make sure to escape these whitespaces e.g. name field.Nuts
H
-11

To check if it is empty:

var str = "Hello World!";
if(str === ''){alert("THE string str is EMPTY");}

To check if it is of type string:

var str = "Hello World!";
if(typeof(str) === 'string'){alert("This is a String");}
Hodges answered 19/7, 2014 at 18:15 Comment(2)
Wrong. length is not null. str = ''; str.length == 0 not str.length == null. But on the whole your approach is ok.Gasman
Checking the length property will cause the string primitive to be wrapped in a string object and checking for null is not correct either as it doesn't look for undefined (which is not the same thing). To test for an empty string, simply check it against "" (i.e. if(myString === ""))Heavierthanair

© 2022 - 2024 — McMap. All rights reserved.