As NateDzMtz says, the memory considerations are the same. null and undefined are unique values and don't involve any references into the heap. In this regard, false would have the same effect. As far as which is convenient for programming, since indexing an object with a key that is not found in the object returns undefined, storing undefined as the value almost simulates absence of the key. Of course, a query can be made to distinguish the case that foo has no key bar from the case where it has the key bar but undefined is stored as the value at that key. But if your design is such that those cases don't have different meanings, it's convenient to stifle slots by putting undefined in them. Note that delete can be inefficient in some engines and they are not required by the standard to make it efficient. I think that the conventional meanings of the special values are, more or less: undefined -- maybe was never initialized; isn't associated to any particular data type. null -- no object, where an object might be expected. NaN -- no number, where a number might be expected. false -- just not true, no other meaning. Note that typeof null is "object", even though you can't index null. typeof undefined is "undefined". typeof NaN is "number", even though NaN explicitly and exactly means "Not a Number"! Answer from jack_waugh on reddit.com
๐ŸŒ
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.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ 'null' or 'undefined': what should i use if i want to clear the variable from the memory?
r/learnjavascript on Reddit: 'null' or 'undefined': What should I use if I want to clear the variable from the memory?
June 7, 2023 -

Please consider the following:

var myFruits = ['Banana', 'Apple', 'Strawberry'];
// SOME CODING
// SOME CODING
myFruits = undefined; // Is this better?
myFruits = null; // or is this better?

Further question, what is the distinction between the two? Is there any cases where only null is used or undefined is used? Thanks.

Top answer
1 of 3
5
As NateDzMtz says, the memory considerations are the same. null and undefined are unique values and don't involve any references into the heap. In this regard, false would have the same effect. As far as which is convenient for programming, since indexing an object with a key that is not found in the object returns undefined, storing undefined as the value almost simulates absence of the key. Of course, a query can be made to distinguish the case that foo has no key bar from the case where it has the key bar but undefined is stored as the value at that key. But if your design is such that those cases don't have different meanings, it's convenient to stifle slots by putting undefined in them. Note that delete can be inefficient in some engines and they are not required by the standard to make it efficient. I think that the conventional meanings of the special values are, more or less: undefined -- maybe was never initialized; isn't associated to any particular data type. null -- no object, where an object might be expected. NaN -- no number, where a number might be expected. false -- just not true, no other meaning. Note that typeof null is "object", even though you can't index null. typeof undefined is "undefined". typeof NaN is "number", even though NaN explicitly and exactly means "Not a Number"!
2 of 3
5
In my opinion I typically would use null to denote the absence of the variable for purposes of debugging. It helps with identifying that the variable was intentionally set to a null value as to not be confused with the variable not being defined in the first place. Additionally, using null can be useful when you want to explicitly assign a "no value" state to a variable. This can be helpful in scenarios where you want to differentiate between an intentional absence of a value and a variable that has not been assigned any value yet. On the other hand, undefined is often used by JavaScript itself to indicate that a variable has been declared but has not been assigned any value. It is the default value for uninitialized variables. In most cases, you don't need to explicitly set a variable to undefined because JavaScript does it automatically. However, it's worth noting that both null and undefined have similar behaviors when it comes to memory management. Assigning either of them to a variable will release the memory occupied by the previous value and make the variable eligible for garbage collection. In conclusion, while both null and undefined can be used to clear a variable from memory, null is typically preferred when you want to denote an intentional absence of value, while undefined is automatically assigned by JavaScript when a variable is declared but not assigned a value.
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ use empty string, null or remove empty property in api request/response?
r/reactjs on Reddit: Use empty string, null or remove empty property in API request/response?
March 4, 2023 -

we had an argue about this on our team, I wonder what approach should we consider? what is the better?

We have a user interface like this:

interface User {
name:string;
family?:string;
age:number;

family name is optional, so our backend developer sends us this json data for those users that didnt filled the family:

{name: "john",
family:"",
age:18
}

and in another object's case they sends null for the optional props...

We have been confused with this not having a solid convention from the backend team! what approach is the better? I think the right way is just removing optional property from the json data instead of setting it to null or "" empty string, I mean just dont add that!

๐ŸŒ
Reddit
reddit.com โ€บ r/askprogramming โ€บ should i return null or an empty object?
r/AskProgramming on Reddit: Should I return null or an empty object?
July 25, 2023 -

My company uses files that are essentially merged XML files into one. I wrote a pretty basic parser and node object that contains the tag name, text, and child node objects. Recently I ran into an error where the file couldn't be found, and my function that searches for child nodes returned null (as it should). But it caused a runtime error, so I'm trying to figure out the best way to address issue. Should I return an empty object so that the code doesn't crash, or should I continue returning null and wrap it in a try/catch?

๐ŸŒ
Reddit
reddit.com โ€บ r โ€บ ProgrammerHumor โ€บ comments โ€บ a7racq โ€บ javascript_empty_string_vs_0_vs_null_vs_undefined
JavaScript: "" (Empty String) vs. 0 vs. null vs. undefined
April 24, 2018 - Toilet Paper Illustration of JavaScript: "" vs. 0 vs. null vs. undefined ... Initially posted by Stefan Baumgartner, then I did my own modification by introducing Empty String "" in the comparison.
Find elsewhere
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Operators โ€บ null
null - JavaScript | MDN
JavaScript is unique to have two nullish values: null and undefined. Semantically, their difference is very minor: undefined represents the absence of a value, while null represents the absence of an object.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ null, undefined, empty string, reference error not defined
r/learnjavascript on Reddit: null, undefined, empty string, reference error not defined
January 27, 2023 -
let u; 
let n = null;
let e = '';

console.log(`u: ${u}`) // undefined
console.log(`n: ${n}`) // null
console.log(`n: ${typeof n}`) // Object type
console.log(`e: ${e}`) //
// console.log('x: ' + x) //Reference error

e = 44;
console.log(`e: ${e}`)
u = 44;
console.log(`u: ${u}`)
n = 44;
console.log(`u: ${u}`)

Why does this have to be so confusing compared to other languages? T-SQL either has an empty value or null.

What would be the purpose of using these in a real world scenario and what is really the difference between undefined vs the reference error of not defined?

I get that you get a reference error because it wasnt "technically defined" inside a let x but why can't javascript dynamically make up for this and why does it use pretty much the same language of undefined for the variables of x and u?

๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ basic js question: when to check for undefined, null, etc
r/javascript on Reddit: Basic JS question: when to check for undefined, null, etc
September 11, 2016 -

So I'm usually more of a server side developer, but lately I've been working with more of the client code at work. I understand what undefined and null are in JavaScript, but I find myself always checking for both of them. In fact, when checking if a String property exists, I end up writing this:

if(value !== undefined && value !== null && value !== '')

I figure there is a better way than this, and it's probably because I'm not 100% clear of when to check for what. So if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.

Top answer
1 of 5
28

TL;DR: Use value != null. It checks for both null and undefined in one step.

In my mind, there are different levels of checking whether something exists:

0) 'property' in object - Returns true if the property exists at all, even if it's undefined or null.

  1. object.property !== undefined - Returns true if the property exists and is not undefined. Null values still pass.

  2. object.property != null - Return true if the property exists and is not undefined or null. Empty strings and 0's still pass.

  3. !!object.property - Returns true if the property exists and is "truthy", so even 0 and empty strings are considered false.

From my experience, level 2 is usually the sweet spot. Oftentimes, things like empty strings or 0 will be valid values, so level 3 is too strict. On the other hand, levels 0 and 1 are usually too loose (you don't want nulls or undefineds in your program). Notice that level 1 uses strict equality (!==), while level 2 uses loose equality (!=).

2 of 5
16

I would just say

if (value) {
  // do stuff
}

because

'' || false
// false
null || false
// false
undefined || false
//false

Edit:

Based on this statement

I end up writing this: if(value !== undefined && value !== null && value !== '')

I initially assumed that what OP was really looking for was a better way to ask "is there a value?", but...

if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.

If you're looking to see if something is "truthy":

if (foo.bar) {
  alert(foo.bar)
}

This won't alert if value is '', 0, false, null, or undefined

If you want to make sure something is a String so you can use string methods:

if (typeof foo.bar === 'string') {
  alert(foo.bar.charAt(0))
}

This won't alert unless value is of type 'string'.

So.. "when to check for undefined vs null"? I would just say, whenever you know that you specifically need to check for them. If you know that you want to do something different when a value is null vs when a value is undefined, then you can check for the difference. But if you're just looking for "truthy" then you don't need to.

Top answer
1 of 16
5789

You can just check if the variable has a truthy value or not. That means

if (value) {
    // do something..
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if (typeof foo !== 'undefined') {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

2 of 16
457

This question has two interpretations:

Check if the variable has a value
Check if the variable has a truthy value

The following answers both.

In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:

 โ•ญโ”€ nullish โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ•ญโ”€ not nullish โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”
โ”‚ undefined โ”‚ null โ”‚ false โ”‚ 0 โ”‚ "" โ”‚ ... โ”‚ true โ”‚ 1 โ”‚ "hello" โ”‚ ... โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”˜
 โ•ฐโ”€ falsy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€ truthy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Check if value is nullish (undefined or null)

Use one of the following depending on your coding style:

if (value == null)                         { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined)                    { /* value is nullish */ }
if ((value ?? null) === null)              { /* value is nullish */ }

Notes:

  • The == operator works because it has a special case for null vs undefined comparison
  • The === operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately
  • The first and third examples work identically, however the third one is rarely seen in production code
  • The fourth example uses nullish coalescing operator to change nullish values to null for straight forward comparison

Check if value is not nullish

if (value != null)                         { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined)                    { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null)              { /* value is not nullish, although it could be falsy */ }

Check if value is falsy

Use the ! operator:

if (!value) { /* value is falsy */ }

Check if value is truthy

if (value) { /* value is truthy */ }

Data validation

The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:

/*
 * check if value is greater than/equal to 0
 * note that we cannot use truthy check here because 0 must be allowed
 */
[null, -1, 0, 1].forEach(num => {
  if (num != null && num >= 0) {
    console.log("%o is not nullish and greater than/equal to 0", num);
  } else {
    console.log("%o is bad", num);
  }
});

/*
 * check if value is not empty-or-whitespace string
 */
[null, "", " ", "hello"].forEach(str => {
  if (str && /\S/.test(str)) {
    console.log("%o is truthy and has non-whitespace characters", str);
  } else {
    console.log("%o is bad", str);
  }
});

/*
 * check if value is not an empty array
 * check for truthy before checking the length property
 */
[null, [], [1]].forEach(arr => {
  if (arr && arr.length) {
    console.log("%o is truthy and has one or more items", arr);
  } else {
    console.log("%o is bad", arr);
  }
});

/*
 * check if value is not an empty array
 * using optional chaining operator to make sure that the value is not nullish
 */
[null, [], [1]].forEach(arr => {
  if (arr?.length) {
    console.log("%o is not nullish and has one or more items", arr);
  } else {
    console.log("%o is bad", arr);
  }
});
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ how to check for null, undefined, or empty values in javascript
How to check for null, undefined, or empty values in JavaScript - LogRocket Blog
February 14, 2025 - Even if you were to do things in ... whereas JavaScript would simply return undefined. ... Weโ€™ve got an empty array, and then we try to print out the fifth element from the array. This is out of bounds. The result of this code is undefined. Basically, there are three conditions that we want to account for when checking for values that we think could be null or ...
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)
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ is it better to receive null for properties of an object or not receive that field at all?
r/learnjavascript on Reddit: Is it better to receive null for properties of an object or not receive that field at all?
March 24, 2024 -

Hi everyone, hope you're doing well!

I'm working on an Angular project and I have doubt about the response of an API send me.

To simplify, I receive a simple object like this:

{ a: 1, b: 2 }

As I expected a "c" inside this object, I got an undefined error.

So I asked the BE guy to send me the "c" value, even if it hasnt a value, send me as a null, so:

{ a: 1, b: 2, c: null }

I prefer this way because I don't have to wonder if the property doesn't exist inside the object, but rather have it ALWAYS, even tho it's null or another value.

Also helps me defining the interface, so I can say that a property is a number, for example, or null.

Also, I dont have weird situation where I have receive an array of this objects and some have the "c" property and other dont.

Has this approach any downside?

Thanks for your time :)

Top answer
1 of 5
4
Engines can optimize the case when objects have the same properties (the same "shape") so as far as performance goes, its better to have all the properties there, even if they don't have useful values. I quickly dug around in MDN for a quick reference to this but didn't find anything right away. There are a number of articles/blog posts out there about it that tend to go a little deeper into the topic. One includes: https://mathiasbynens.be/notes/shapes-ics The conclusion at the end for TL;DR-ers: Take-aways Weโ€™ve learned how JavaScript engines store objects and arrays, and how Shapes and [inline caches] help to optimize common operations on them. Based on this knowledge, we identified some practical JavaScript coding tips that can help boost performance: Always initialize your objects in the same way, so they donโ€™t end up having different shapes. Donโ€™t mess with property attributes of array elements, so they can be stored and operated on efficiently.
2 of 5
2
For most uses and purposes, undefined (not presnet) and null are pretty much the same. Checking for existence (obj.field) will return false for both null and undefined. Accessing a field that does not exist is not an error, so it also does not matter if it's null or undefined. Optional chaining (?.) and null-ish coalescing (??) will also handle both null and undefined the same. And you can use loose equality with null or undefined to match both (null == undefined). One downside to using null is that it increases the payload size, which might seem insignificant, unless there's a lot of null fields or a lot of traffic. Also helps me defining the interface, so I can say that a property is a number, for example, or null. The interface should be defined by something like OpenAPI spec ideally, then you also don't face this issue and it again doesn't matter if it's null or undefined.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ is my interpretation of null vs. undefined correct?
r/learnjavascript on Reddit: Is my interpretation of null vs. undefined correct?
June 23, 2018 -
  • Undefined: The variable exists, but it has not yet been give a value, and thus it has a default value of undefined.

  • Null: The variable exists only as a reference. It does not yield any value.

Follow-up: Why is it useful to distinguish between null and undefined in javascript?

Top answer
1 of 3
6

This does not completely cover all cases.

Undefined doesn't necessarily mean that a variable exists but hasn't been given a value yet. It's also possible to explicitly give a variable the value of "undefined", and it is sometimes returned when trying to look up an object member that doesn't exist. E.g. when looking up myObj.thisDoesntExist.

Variables that are set to null do return a value: the value being null.

They need to both be taken into account because they behave slightly differently. For example, if you have a function with default arguments, the default argument will be used if you pass undefined (or no argument at all) - but if you pass null, then your null will be used.

2 of 3
2

Not... exactly.

undefined means that either the value of the variable has not yet been defined, OR you've explicitly given the variable the value of undefined.

null is essentially an empty value that's separate from more generic (specific?) empty values, like empty string or zero or empty array. It's the equivalent of saying "this box (variable) that can hold a value currently is empty".

Finally, not defined (not really a value, but worth mentioning) is a special error-case when you try to access a variable before initializing it. For example, if you load an empty page and type in the console console.log(derp), you'll get a message that says "Uncaught ReferenceError: derp is not defined". This final value is a little strange, since it's almost the same as undefined, but won't allow you to access the variable in any format; It doesn't exist yet.

๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ [askjs] why hasn't the null type bug been fixed?
r/javascript on Reddit: [AskJS] Why hasn't the null type bug been fixed?
September 16, 2020 -
typeof null === 'object'; // true 

The rationale I've heard is that it's too late to fix this one becaus an update to a null type would break a lot of old programs.

Ok, so why don't we allow this as a default, but then add the null type if a version check indicates ES2020 or later? I think that could be implement with a top of file statement similar to strict mode.

Only answer I can think of is that everyone is used to it, so it isn't a priority.