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
}
Answer from Brian Dukes on Stack Overflow
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-check-empty-string-checking-null-or-empty-in-js
JavaScript Check Empty String โ€“ Checking Null or Empty in JS
November 7, 2024 - We can easily fix this error by first removing the white spaces using the trim() method before checking for the length of such string to see if itโ€™s empty as seen below: let myStr = " "; if (myStr.trim().length === 0) { console.log("This is an empty string!"); }else{ console.log("This is NOT an empty string!"); } ... Note: If the value is null, this will throw an error because the length property does not work for null.
๐ŸŒ
Retool
community.retool.com โ€บ ๐Ÿ’ฌ app building
Replace empty string to null in form submit, and JS limitation in Changeset Object - ๐Ÿ’ฌ App Building - Retool Forum
December 18, 2023 - I might be asking trivial questions but I really couldn't figure them out In a very simple pgsql form submit, some of foreign key need to be null instead of "" otherwise I get below error My first thought is to use inline js to replace "" with null inside Changeset -> Object -> {{form.data}}, but immediately I get run into a error object.keys() is not a function shown in below screenshot.
๐ŸŒ
Medium
medium.com โ€บ @yi_yuan โ€บ understanding-null-undefined-and-empty-strings-in-javascript-a07959084d
Understanding Null, Undefined, and Empty Strings in JavaScript | by Yi Yuan | Medium
January 8, 2023 - Also, please note that all functions return undefined by default unless itโ€™s been decided to return a specific value instead. An empty string is a string that has nothing inside it. Itโ€™s like a word that has no letters.
Top answer
1 of 16
5116

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
}
2 of 16
1448

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.

Top answer
1 of 2
9

You wrote:

document.getElementById("demo").innerHTML = String(null); //returns an empty string 
document.getElementById("demo").innerHTML = null.toString(); //returns "null" string

But both assertions are false, I am afraid.

String(null) never returns an empty string, rather a primitive of type string whose value is "null".

BTW, the form String(null) should never be used.

new String(null), on the other hand, returns an object, an instance of String (note the uppercase first letter) whose primitive value ([[PrimitiveValue]] internal property) is "null".

null.toString() raises an error in every JS engine I know. Even though null might be considered an object (due to a historical bug), it has no property, therefore no 'method' toString() (I quote the 'method' because there are no methods in JS, really).

Anyway, to be consistent, you could use this :

document.getElementById("demo").innerHTML = whateverVariable || '';

Should whateverVariable be falsy (null, undefined, 0, -0, '', NaN or false), empty string '' will be assigned to document.getElementById("demo").innerHTML.

2 of 2
4

I don't think there's a real convention here; Element.innerHTML is a property that tests the given value to determine what to do. In Safari it behaves like this:

if (value === null || value === '') {
    // remove all contents
} else {
    // parse string representation of value into the elements contents
}

So both "" (empty string) and null are considered the same and the assignment will just remove all contents; I couldn't find conclusive evidence that would suggest other browsers work this way, but it seems very likely that it should be considered an implementation detail that you shouldn't rely upon (see update).

That said, the documented way of clearing an element is by assigning the empty string to this property.

Update

I've found this (inconclusive) email thread about the subject, highlighting that this behaviour is not standardised:

For .innerHTML = null Opera and Internet Explorer act as if the literal string "null" was used. Firefox acts as if "" was used.

Top answer
1 of 5
24

In programming, truthiness or falsiness is that quality of those boolean expressions which don't resolve to an actual boolean value, but which nevertheless get interpreted as a boolean result.

In the case of C, any expression that evaluates to zero is interpreted to be false. In Javascript, the expression value in

if(value) {
}

will evaluate to true if value is not:

null
undefined
NaN
empty string ("")
0
false

See Also
Is there a standard function to check for null, undefined, or blank variables in JavaScript?

2 of 5
9

The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:

+--------------------------------------------------------------------------+
| Argument Type | Result                                                   |
|---------------+----------------------------------------------------------|
| Undefined     | false                                                    |
|---------------+----------------------------------------------------------|
| Null          | false                                                    |
|---------------+----------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion).    |
|---------------+----------------------------------------------------------|
| Number        | The result is false if the argument is +0, โˆ’0, or NaN;   |
|               | otherwise the result is true.                            |
|---------------+----------------------------------------------------------|
| String        | The result is false if the argument is the empty String  |
|               | (its length is zero); otherwise the result is true.      |
|---------------+----------------------------------------------------------|
| Object        | true                                                     |
+--------------------------------------------------------------------------+

From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.

If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:

if (!fields || fields.length === 0)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-check-empty-undefined-null-string-in-javascript
How to Check empty/undefined/null String in JavaScript? - GeeksforGeeks
July 11, 2025 - // function to check string is empty or not function checking(str) { if(str.replace(/\s/g,"") == "") { console.log("Empty String") } else{ console.log("Not Empty String") } } checking(" "); checking("Hello Javascript");
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-null-is-converted-to-string-in-javascript
How null is converted to String in JavaScript?
We can use this technique to convert null to string. We use + operator to concatenate the null and empty string("").
๐ŸŒ
Meteor
forums.meteor.com โ€บ help
Null vs empty string? - help - Meteor Forum
June 22, 2015 - For example I have one function var myFun = function(){ .............. do something ............. if(data..){ return data; }else{ return null; // or empty string ' '; } } I should be reโ€ฆ
๐ŸŒ
Zipy
zipy.ai โ€บ blog โ€บ how-do-i-check-for-an-empty-undefined-null-string-in-javascript
how do i check for an empty undefined null string in javascript
April 12, 2024 - When checking for empty, undefined, or null strings, be mindful of the nuances and edge cases in JavaScript: Use strict equality (===) for precise checks: This avoids unintended type coercion that might lead to incorrect evaluations.
๐ŸŒ
W3docs
w3docs.com โ€บ javascript
How to Check for Empty/Undefined/Null String in JavaScript
When the string is not null or undefined, and you intend to check for an empty one, you can use the length property of the string prototype, as follows: ... Another option is checking the empty string with the comparison operator โ€œ===โ€. ... The JavaScript strings are generally applied for either storing or manipulating text.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ javascript empty string is not empty
r/learnjavascript on Reddit: Javascript empty string is not empty
March 2, 2022 -

They closed my question on SO because it's not reproducible, but that's exactly why I posted, because code isn't behaving as it should.

Anyway, I 'm receiving a JSON result from a web service. It looks something like this:

{ "data": [{ "id": "123ABC", "name" : "Test 1" }, { "id": "", "name" : "Test 2" }] }

I 'm looping through the data array and need to determine if an id exists or not:

for( const item of data ) {
    if( item.id !== null && item.id.trim().length > 0 ) {
        doSomething();
    } else {
        doSomethingElse();
    }
}

My problem is that doSomething() fires for the first item ("123ABC") but also fires for the second where the id is empty.

I've tried spitting out the values for the second item:

console.log("NULL ", item.id === null);
console.log("EMPTY ", item.id.trim().length === 0);

and results are

NULL  false
EMPTY  false

so I'm wondering if there's something strange about the id value.

๐ŸŒ
GitHub
github.com โ€บ colinhacks โ€บ zod โ€บ issues โ€บ 1721
How to transform empty strings into null? `z.emptyStringToNull()` ยท Issue #1721 ยท colinhacks/zod
December 18, 2022 - import { afterAll, beforeAll } from 'vitest'; import { z } from 'zod'; describe('Test zod validations', () => { it('should correctly handles a valid ISO date-string', () => { const valid_from = '2022-12-14T22:07:10.430805+00:00'; const valid_to = undefined; <-- this works const valid_to = null; <-- this works const valid_to =""; <-- this is not working const schema = z.string().datetime({ offset: true }).nullish(); expect(schema.parse(valid_from)).toStrictEqual(valid_from); expect(schema.parse(valid_to)).toStrictEqual(valid_to); }); });
Published ย  Dec 18, 2022
๐ŸŒ
DEV Community
dev.to โ€บ akshatsoni26 โ€บ decoding-javascript-mastering-null-undefined-and-empty-values-hld
Decoding JavaScript: Mastering Null, Undefined, and Empty Values - DEV Community
August 4, 2024 - Note: typeof null returns object, which is a known quirk in JavaScript due to legacy reasons. undefined represents a variable that has been declared but hasn't been assigned a value yet. let myUndefinedVariable; console.log(myUndefinedVariable); // Output: undefined console.log(typeof myUndefinedVariable); // Output: "undefined" function myFunction(param) { console.log(param); } myFunction(); // Output: undefined ยท An empty string is a valid string with a length of zero.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how do i check for an empty/undefined/null string in javascript?
How do I Check for an Empty/Undefined/Null String in JavaScript? | Sentry
function isEmpty(value) { return (value == null || (typeof value === "string" && value.trim().length === 0)); } console.log(isEmpty("cat")); // false console.log(isEmpty(1)); // false console.log(isEmpty([])); // false console.log(isEmpty({})); // false console.log(isEmpty(false)); // false console.log(isEmpty(0)); // false console.log(isEmpty(-0)); // false console.log(isEmpty(NaN)); // false console.log(isEmpty("")); // true console.log(isEmpty(" ")); // true console.log(isEmpty(null)); // true console.log(isEmpty(undefined)); // true