4154

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

8
  • 5
    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/… Commented Oct 2, 2008 at 15:16
  • Check this one : stackoverflow.com/a/36491147/7026966 Commented May 13, 2019 at 10:58
  • 2
    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. Commented Oct 16, 2019 at 12:47
  • str.length > -1 Commented Jan 31, 2021 at 4:29
  • 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 undefined Commented Aug 11, 2021 at 14:59

56 Answers 56

1
2
10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm pretty sure test === "" is equivalent, and it's shorter.
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.

1 Comment

You are checking for truthiness, here, which is bit more complicated than merely checking for empty strings, undefined or null
7

I usually use something like:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

1 Comment

== operator is not strict. So if str == "", str can be null, undefined, false, 0, [], etc..
7

Try this

str.value.length == 0

2 Comments

"".value.length will cause an error. It should be str.length === 0
This trow a TypeError If str is equal to undefined or null
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

3 Comments

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.
Please don't pollute prototypes.
It's generally considered bad practise to use monkey-patching like this.
7

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

const isNonEmptyString = (val) => typeof val === 'string' && !!val

Comments

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

1 Comment

This answer should be pinned to the top.
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");

Comments

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

1 Comment

The first condition works for any falsey value, not just undefined. This answer is not checking for type.
5

Try this code:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

1 Comment

What is the purpose of (strValue.trim()).length === 0) at the end of the condition? Isn't it redundant with strValue.trim() === ""?
5

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

const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0

Comments

4

I prefer to use not blank test instead of blank

function isNotBlank(str) {
   return (str && /^\s*$/.test(str));
}

3 Comments

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.
IsNotBlank is a standard function and very popular function in StringUtils commons.apache.org/proper/commons-lang/apidocs/org/apache/…
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.
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.

Comments

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:

Comments

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

1 Comment

A major flaw: this regex matches the string literal "null". (/(null|undefined|^$)/).test("null")
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

1 Comment

The third solution is basically wrong when input is not a number, so that parsing result will be NaN which is also falsy.
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"));

Comments

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.

Comments

3

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.

Comments

2

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

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

Comments

2
function isNull(input) {
  return input == null;
}

function isEmpty(input) {
  return (!input && input !== 0) || input.length === 0 || (Object.getPrototypeOf(input) === Object.prototype && Object.getOwnPropertyNames(input).length === 0);
}

function isBlank(input) {
  return isNull(input) || isEmpty(input);
}

function isPresent(input) {
  return !isBlank(input);
}

isPresent(undefined) === false &&
isPresent(null) === false &&
isPresent("") === false &&
isPresent([]) === false &&
isPresent({}) === false &&
isPresent(0) === true &&
isPresent(1) === true &&
isPresent("Hello") === true &&
isPresent([1, 2, 3]) === true &&
isPresent({ name: "John" }) === true
// => true

PS: You can copy past this code into your browser console to verify

Comments

1

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
)

Comments

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:

Comments

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

Comments

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

2 Comments

This will return true, even for strings that aren't empty that contain whitespace, such as " "
I agree, but most of the time you do need to make sure to escape these whitespaces e.g. name field.
-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");}

2 Comments

Wrong. length is not null. str = ''; str.length == 0 not str.length == null. But on the whole your approach is ok.
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 === ""))
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.