By casademora


2008-09-30 17:17:45 8 Comments

I saw this question, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

30 comments

@Sazid 2014-05-06 06:38:00

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");
    }

@Kamil Kiełczewski 2019-12-31 18:48:11

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

@WebWanderer 2020-01-24 19:15:24

This is really awesome! I love seeing all of this laid out! Thank you!

@Abhishek Luthra 2020-02-10 08:34:31

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

@nerez 2020-04-28 04:15:14

what happens if value = false or value = 0. will you return the correct response according to the question?

@Nagnath Mungade 2019-12-05 10:14:19

Check all the below scenarios:

  1. null

  2. undefined

  3. 0

  4. "" (the empty string)

  5. false

  6. NaN

@Davi Daniel Siepmann 2019-10-23 21:13:57

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

@Zhuravlev A. 2019-11-29 14:34:28

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/…

@japesh singhal 2019-10-18 09:02:47

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

@Moshii 2017-08-17 06:51:14

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.

@Erich 2020-02-13 15:56:17

_.isEmpty(" "); // => false

@Moshii 2020-03-25 07:34:30

@Erich Because " " is not empty. _.isEmpty(""); returns true.

@Erich 2020-03-26 00:30:23

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.

@Luca C. 2017-06-02 08:33:53

To check if it is exactly an empty string:

if(val==="")...

To check if it is an empty string OR a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):

if(!val)...

@Thaddeus Albers 2015-06-10 08:44:51

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:

@KanimozhiPalanisamy 2015-03-25 09:37:11

<html>
    <head>
        <script lang="javascript">

            function nullcheck()
            {
                var n = "fdgdfg";
                var e = n.length;
                if (e == 0)
                {
                    return true;
                }
                else
                {
                    alert("success");
                    return false;
                }
            }
        </script>
    </head>

    <body>
        <button type="submit" value="add" onclick="nullcheck()"></button>
    </body>
</html>

@Peter Mortensen 2020-03-09 00:04:24

An explanation would be in order.

@Gaurav 2014-04-08 09:37:02

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")
}

@T.Todua 2014-02-27 20:31:28

Function:

function is_empty(x)
{
    return (
        (typeof x == 'undefined')
                    ||
        (x == null)
                    ||
        (x == false)  //same as: !x
                    ||
        (x.length == 0)
                    ||
        (x == "")
                    ||
        (x.replace(/\s/g,"") == "")
                    ||
        (!/[^\s]/.test(x))
                    ||
        (/^\s*$/.test(x))
    );
}

PS: In JavaScript, don't use line break after return;

@DanV 2014-03-21 12:13:20

Any chance you could explain what each check is doing? :)

@Bennett McElwee 2014-04-01 22:39:44

-1 They are testing for different things. It makes no sense to put them all into one if statement.

@Scott Marcus 2016-01-28 21:57:32

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.

@user2086641 2013-08-09 10:10:50

I usually use something like this,

if (!str.length) {
    // Do something
}

@Adrian Hope-Bailie 2014-02-20 10:16:43

Fastest if you know that the variable is a string. Throws an error if the variable is undefined.

@Abimael Martell 2014-04-01 00:18:37

@AdrianHope-Bailie why would you test an undefined variable?

@Adrian Hope-Bailie 2014-04-01 08:28:04

@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");}

@Abimael Martell 2014-04-01 18:56:37

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.

@Wab_Z 2013-05-15 14:55:15

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.

@JHM 2013-05-14 10:18:36

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; } }]
];

@Scott Marcus 2016-01-28 22:05:29

If you simply stop using == and use ===, then this solves the problem if(s === "").

@Andron 2013-05-08 17:15:40

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.

@Bennett McElwee 2014-04-01 22:44:46

Huh? If you are expecting a string, empty(0) and empty(7) should return the same value.

@Andron 2014-04-02 11:24:52

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

@Bennett McElwee 2014-04-02 21:15:56

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.

@Andron 2014-04-03 12:14:44

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.

@Bennett McElwee 2014-04-03 22:57:46

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.

@GibboK 2013-02-10 10:20:48

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

var myString = 'hello'; 
if(myString.charAt(0)){
    alert('no empty');
}
alert('empty');

@Will 2011-06-01 15:40:33

I use a combination, and the fastest checks are first.

function isBlank(pString) {
    if (!pString || pString.length == 0) {
        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);
}

@Nicholi 2011-10-27 21:49:10

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');

@mricci 2012-07-19 02:00:00

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.

@karthick.sk 2011-03-30 13:34:22

All the previous answers are good, but this will be even better. Use the !!(not not) operator.

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 string "0" and whitespace " ".

@Mene 2011-04-03 13:04:35

Why is this "even better"?

@Bluebaron 2014-08-03 16:57:06

It's not a nice trick, it's the way it should be done. This is the correct way. Javascript defines the truth of "" and null as false.

@Peter Olson 2014-12-19 18:28:04

Is there any difference between the behavior of if(str) and if(!!str)?

@John Ruddell 2015-03-10 23:00:24

@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

@Dario Oddenino 2016-02-11 10:56:14

This is the solution I always use. !!str.trim() to make sure the string is not made of whitespaces only.

@shinzou 2016-10-17 21:28:01

Not not looks like a hack, Boolean(str) is a lot more readable and less "wtfish".

@xehpuk 2017-03-15 11:44:34

@JohnRuddell This doesn't answer Peter's question and it doesn't look like something I would want to do.

@John Ruddell 2017-03-15 18:05:39

@xehpuk not sure I follow what you mean. the not not operator is enforcing a boolean type.. aka true or false. If you want to enforce a boolean type use the not not operator. Essentially there isn't a difference between the two in an if check. But its especially useful when you want a boolean flag that you use in more than one place. Thats what my comment is referring to although not explicitly stated.

@xehpuk 2017-03-15 19:34:59

@JohnRuddell Yeah, so this answer is not very useful. And for the boolean variable, why not var any = Boolean(str1 && str2 && str3);? Should be clearer and faster.

@John Ruddell 2017-03-16 19:05:57

@xehpuk no it is not faster at all. you should look at what Boolean does

@xehpuk 2017-03-16 19:12:20

@JohnRuddell Boolean(value) converts any value to a boolean value. Straightforward. !! converts any value to a boolean value and negates it twice.

@John Ruddell 2017-03-17 00:28:21

@xehpuk You are not understanding the benefit of !!. Boolean is a javascript class. It has a bunch of methods that it has. When you use Boolean as a function you are still allocating memory for all of its methods as well as its base class portion. This is more heavy than a simple operator boolean check which is why !! is more efficient.

@John Ruddell 2017-03-17 04:22:32

@xehpuk Boolean is a primitive type.. when you call Boolean(something) you are invoking the constructor function that corresponds to the Boolean primitive type... (aka not using the new keyword) to explicitly cast a value as truthy or falsy (except it returns a Boolean Object and not a true boolean... If you look at the MDN declaration of what Boolean is you can see pretty easily what it does. but that aside heres a link that does a speed comparison between Boolean and !! sitepoint.com/javascript-double-negation-trick-trouble

@Oliver Spryn 2017-04-14 17:27:57

Note that !! is not an operator. It is one operator applied twice.

@Lluis Martinez 2018-06-20 14:11:39

Looks like a hack

@FranCarstens 2018-08-24 15:10:12

@Lluis Martinez, legible, modern JS; it would look even better if OP had written: const someFunc = () => {}; !!str && someFunc()

@Lluis Martinez 2018-08-27 08:41:51

Modern JS - no doubt. Legible is a matter of taste. To me it's not :-)

@Ozgur Bar 2019-03-20 08:32:50

!!bang bang, you're boolean!!

@Arth 2019-05-30 09:17:47

@JohnRuddell aren't the bangs redundant in var any = (!!str1 && !!str2 && !!str3)? Won't the && operator convert the operands to booleans anyway?

@John Ruddell 2019-05-30 15:03:20

@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 differently

@Arth 2019-05-31 08:27:30

@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?

@Alvin Thompson 2019-08-27 17:10:44

@Arth @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.

@Alvin Thompson 2019-08-27 17:24:02

@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".

@Arth 2019-08-28 08:42:05

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

@Arth 2019-08-28 08:46:47

@JaredPrice I'm not so sure about that.. if(!!''){} and if(''){} should give the same result, and are equivalent in my sanity tests on jsfiddle

@Jared Price 2019-09-03 16:27:20

@Arth strange, I swear this is what I was seeing in my console the other day. Oh well. Let me just delete my comment.

@Alex 2020-03-25 09:09:13

This is good as it allows to not use .length property, which exists on Array and String.

@Muhammad Salman 2010-08-06 16:28:06

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.

@Jet 2010-07-09 18:52:40

I use:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case typeof(e) == "undefined":
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

@Jeff Davis 2012-04-20 13:11:58

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.

@xarlymg89 2018-01-25 10:06:52

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.

@Lucas 2018-04-17 11:15:22

The typeof in the switch did not work for me. I added a if (typeof e == "undefined") test and that works. Why?

@beeThree 2020-02-25 03:01:19

@Lucas 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)

@Boris J. 2020-03-27 19:34:20

Could we use case undefined: instead of case typeof(e) == "undefined":?

@oem 2010-05-31 14:57:38

You could also go with regular expressions:

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

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

@Orpheus 2015-05-11 16:38:40

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.

@Chris Noe 2008-09-30 17:20:57

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.

@Constantin 2008-09-30 19:21:20

Bad idea. You'll get true if strVar is accidentally assigned 0.

@Useless Code 2015-06-13 17:52:25

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.

@Valentin Heinitz 2015-12-27 13:57:03

The check fails if undefined. So if(str) works better

@Scott Marcus 2016-01-28 22:02:28

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

@Harshit Agarwal 2019-04-11 12:16:21

As of now there is no direct method like string.empty to check whether a string is empty or not. But in your code you can use a wrapper check for an empty string like:

// considering the variable in which your string is saved is named str.

if (str && str.length>0) { 

  // Your code here which you want to run if the string is not empty.

}

Using this you can also make sure that string is not undefined or null too. Remember, undefined, null and empty are three different things.

@whoami 2019-04-17 15:45:49

It would throw an error on null or undefined cause we should not be directly doing an operation on a variable which is null or undefined - check for str does exist before doing this as stated in other answers & also note that this would work on let abc = '' but not on let abc = ' ', these two are different.

@RobG 2019-10-16 12:51:02

Consider let rand = ()=>Math.random(), then rand && rand.length > 0) returns false, but clearly fn is not "empty". I.e. it returns false for any function that has no format parameters.

@Harshit Agarwal 2019-11-15 05:07:22

@RobG Math.random() returns a number and not a string. And this answer is about strings. ;-)

@V1NNY 2019-05-10 21:33:38

Try this:

export const isEmpty = string => (!string || !string.length);

@Alireza 2017-10-07 02:33:01

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

@John Montgomery 2020-02-03 22:46:52

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.

@Doug 2010-07-22 15:30:53

Try this

str.value.length == 0

@AndFisher 2016-12-14 10:57:16

"".value.length will cause an error. It should be str.length === 0

@RousseauAlexandre 2019-09-11 07:08:20

This trow a TypeError If str is equal to undefined or null

@tfont 2016-03-31 08:29:46

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.

@SvdSinner 2016-06-16 14:10:34

Checking for undefined would need to be moved to first in the checks, or undefined items will throw exceptions on the earlier checks.

@tfont 2016-06-17 15:17:25

Completely agree! NICE CATCH. I will edit my above answer!

@RobG 2019-10-16 12:52:29

str.length === 0 returns true for any function that has no formal parameters.

@Ates Goral 2008-09-30 19:17:32

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

if (!str.length) { ...

@Pic Mickael 2018-09-11 13:50:35

Wouldn't that throw an exception is str is null?

@Ates Goral 2018-09-12 03:25:43

@PicMickael Yes! So would str.Empty.

Related Questions

Sponsored Content

95 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6848528 View
  • 8427 Score
  • 95 Answer
  • Tags:   javascript arrays

67 Answered Questions

[SOLVED] How to replace all occurrences of a string?

30 Answered Questions

[SOLVED] How can I determine if a variable is 'undefined' or 'null'?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

61 Answered Questions

[SOLVED] Avoiding != null statements

41 Answered Questions

3 Answered Questions

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

63 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

Sponsored Content