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/typescript › undefined vs null
r/typescript on Reddit: Undefined vs null
February 27, 2023 -

Since switching to TypeScript I have been using a lot of optional properties, for example:

type store = {
  currentUserId?: string
}

function logout () {
  store.currentUserId = undefined
}

However my coworkers and I have been discussing whether null is a more appropriate type instead of undefined, like this:

type store = {
  currentUserId: string | null
}

function logout () {
  store.currentUserId = null
}

It seems like the use of undefined in TypeScript differs slightly from in Javascript.

Do you guys/girls use undefined or null more often? And, which of the examples above do you think is better?

🌐
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/javascript › null vs undefined
r/javascript on Reddit: null vs undefined
January 13, 2018 - Just adding on: Notice how when you initialize a variable, it is always automatically set to undefined at first? It's because it literally does not have a definition. Things that are null do have a definition. They are defined as void. ... Oh man the null thing I didn't know about. Which has led to me go read this whole SO question: https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
🌐
Reddit
reddit.com › r/javascripttips › why does javascript have both null and undefined?
r/JavaScriptTips on Reddit: Why does JavaScript have both null and undefined?
November 11, 2022 -

Most programming languages have a single value to indicate the absence of something, which is often called null and is used to represent a variable that has no value associated with it.

But JavaScript is different. Someone who is just starting out with JavaScript or coming from a different language usually finds it hard to understand, why there are two values that indicate absence: null and undefined

Check out the post to learn how these two are different.

🌐
Reddit
reddit.com › r › programming › comments › 6fszz › javascript_undefined_vs_null
r/programming - JavaScript undefined vs. null
April 15, 2008 - Explicitly check for if(thing == null): JS' coercion rules will coerce an undefined value into a null in that case (but not if you're using ===). Always. ... NULL IS UNKNOWN ITS NOT TRUE OR FALSE! Well.. hardcore C heads can think what they want, hardcore JavaScript heads will tell you that null is an object.
🌐
Reddit
reddit.com › r/learnjavascript › javascript basics undefined vs null
r/learnjavascript on Reddit: JavaScript Basics undefined vs null
January 11, 2021 - I've been using javascript for 8 years, for reference ... Null is a primitive, but it is special, it is an object like more complex structural types, like object itself, arrays, and functions.... The strict equality, or 'identity' operator gives you the real deal, and is almost always what your want, not performing any type conversions: typeof null // "object" typeof undefined // "undefined" null === undefined // false null == undefined // true -- basically just saying both these values are 'falsy' or equal to nothing
🌐
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?
August 2, 2019 -
  • 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.

Find elsewhere
🌐
Reddit
reddit.com › r/learnjavascript › not sure when to use undefined and null in javascript?
r/learnjavascript on Reddit: Not sure when to use Undefined and Null in JavaScript?
January 22, 2017 - ... When the typeof keyword is used on undefined it outputs "undefined" which is correct. When typeof is used on null it outputs "object "which is not correct and is a flaw in the language that was never fixed.
🌐
Reddit
reddit.com › r/javascript › handling null and undefined in javascript
r/javascript on Reddit: Handling null and undefined in JavaScript
January 12, 2020 - Null means "this has no value and the programmer intends that". Undefined means "this has no value because it has not been assigned by the programmer". ... Undefined mean this has not be declared by the programmer.
🌐
Reddit
reddit.com › r/programmerhumor › what is the difference between null and undefined in javascript?
r/ProgrammerHumor on Reddit: What is the difference between null and undefined in JavaScript?
August 12, 2020 - There is also difference between undefined (the constant) and property which doesn't exist (never set) ... I hate you. I was so happy about the pic and though I understand JS now. Okay, scratch that, I hate JS. ... For anything funny related to programming and software development. ... For anything funny related to programming and software development. ... Chat about javascript and javascript related projects.
🌐
Reddit
reddit.com › r/javascript › [askjs] why doesn't js deprecate undefined and replace everything with null?
r/javascript on Reddit: [AskJS] Why doesn't JS deprecate undefined and replace everything with null?
April 16, 2022 -

I never understood why JS makes a distinction between the two. Other programming languages don't have undefined and only have a null value.

I understand that they represent different things, but in practice they are used in exactly the same way. Accessing a property on an undefined/null value gives the same error Cannot read property x of undefined/null. I have never found it useful to make a distinction between the two and I usually have to always make double checks like if (x === undefined || x === null).

Was this just a poor design decision that is here to stay? If someone actually has a use case for knowing the distinction between null vs undefined, I would like to hear it.

🌐
Reddit
reddit.com › r/learnjavascript › is my interpretation of null, undefined and nan correct?
r/learnjavascript on Reddit: Is my interpretation of null, undefined and NaN correct?
February 29, 2024 -

Suppose I am collecting a sample of movie ratings from 1000 random people to see if they are good. The movies are rated as Number types from -10 to 10.

For example

  1. undefined = no such movie (no value exists)

  2. null = haven't watched the movie (exists, but left undeclared)

  3. 0 = no opinion about the movie (normal value)

  4. NaN = I can't tell if I like it or hate it (indeterminate or invalid number)

Is it correct and is the system good? Tell me in the comments below!

Top answer
1 of 6
10
You're in the ballpark. As a general matter, I would put it like this: undefined - there is nothing because no value has been set null - there is nothing because a value is intentionally absent NaN - an invalid number, it does not exist on the number line, like 0 / 0 or parseInt('banana') Then in your specific use case, I would expect trying to get a rating for a movie that doesn't exist to throw an error or for the movie to be undefined. I would expect any unsubmitted rating to be undefined. It has not been submitted, so it has not been set. I would not expect your app to make use of null or NaN. NaN in particular would be weird to deliberately use in your code. It is essentially an error state. I would also caution about getting too clever with null and undefined. They both mean "nothing" and are not used consistently one way or another at the language level. Having both as a potential value for some property and asking your fellow devs to parse which means what will just lead to confusion.
2 of 6
7
I would disagree with you on undefined, null and NaN. Undefined is when something is declared bit returns no value. const  value; is undefined. Console.log(function (){}); Is undefined and  const obj = {"a": 1}; obj.b; is undefined. Basically you are trying to access a value or reference that does not exist. "I have no reference to the movie you are talking about." Null on the other hand is a deliberate assignment that something does not have a value or reference. Let a = null; "That move does not exist". NaN is any value that is not a number. "How would you rate them movie between -10 and 10?" "Yes."
🌐
DEV Community
dev.to › sduduzog › null-vs-undefined-what-to-choose-what-to-use-11g
null vs undefined? What to choose? What to use? - DEV Community
August 23, 2023 - When a javascript object is being serialized, all undefined properties are discarded, remember 'undefined' means a property is yet to be assigned a value. But null on the other hand is known by JSON as its a valid JSON data type
🌐
DEV Community
dev.to › zahrakhadijha › the-difference-between-null-and-undefined-in-javascript-51gc
The Difference Between Null and Undefined in JavaScript - DEV Community
November 24, 2021 - If you were to compare the two in JavaScript, implicitly they're the same because JavaScript considers them both as empty values. But since they are both different data types, if you compare them explicitly, they will result in a falsey value. ...
Top answer
1 of 7
26

both are falsy values that denote absence of data, the only difference is apparently whether or not it was "intentional"

The main problem with Javascript having both null and undefined is that they are used inconsistently, even in standardised APIs. There is no absolute authority which says what each should be used to mean or indicate, and so different programmers imbue them with different meanings. Library code mostly has to treat them the same way, because there is no agreed standard for how they should be treated differently.

Perhaps to you, null means an "intentionally" missing value and undefined means an "unintentionally" missing value, but this isn't universal. The ECMAScript specification doesn't seem to have anything to say on the subject. MDN advises that null means "the intentional absence of any object value" but doesn't give the opposite advice for undefined. And as an example, canvas.getContext('2d') returns null when the same canvas is already in use in a 3D context, something very unlikely to be done intentionally.

Worse, "intentionally missing" isn't as clear a distinction as you might think. For example, function parameters take the value undefined when no argument is provided, but an argument could be missing either intentionally or unintentionally. Likewise, map.get(missingKey) returns undefined, but the key could be absent either intentionally or unintentionally. (Meanwhile, localStorage.getItem returns null instead in the same case.) The intent where a value is produced may also be different than where it is used.

As a result, if you come across some variable which might hold either an object or null or undefined, you will have to read the comments (hopefully there are some!) to figure out what the author intended by that. Perhaps the author didn't even intend to treat them differently, just there is a mix of undefined and null because those values came from different places and there was no need to unify them.

If instead there was a language-wide authoritative standard which said undefined means one thing and null means another, then this would be less of a problem, although there would still be code which doesn't follow the standard. That said, if you can think of a clear difference between what these two values should mean in your language, then you can probably think of better names for these values which would communicate those meanings.

2 of 7
7

It is useful but not necessary and there are better alternatives.

Dynamically typed languages have the limitations that they can only discover concrete types of values. That means they cannot differentiate between levels of a value being undefined: a function taking a value: Option[T] = None cannot find out whether it received the default None or was passed one if T is itself some Option[T'].

This can be practically fixed by having more than one "not defined" value: A function taking a value: T = undef can trivially separate the case of default undef and passed in None.
Of course this only shifts the problem: While for many practical problems eliminating half the collisions is enough, collisions still occur. A function that has to operate on both default and passed in undef/None still cannot separate the cases.

A more thorough approach is to allow/encourage defining new "not defined" values/types for each use. For example, Python has the idiom of using a hidden, bare object() as needed.

# placeholder with unique identity
_no_default = object()

def find(predicate, values, default = _no_default):
   ...

Of course a language can provide tools and syntactic sugar to make this simpler.

🌐
Reddit
reddit.com › r/learnjavascript › what is the difference between null and undefined in javascript?
r/learnjavascript on Reddit: What is the difference between null and undefined in JavaScript?
August 28, 2013 - Someone correct me if I'm mistaken but I believe that Undefined means that nothing has ever been assigned to that variable. Null is an object, which is just saying that this exists and has been defined but has no value/properties.
🌐
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
December 20, 2017 -

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.

🌐
CoreUI
coreui.io › blog › what-is-the-difference-between-null-and-undefined-in-javascript
What is the Difference Between Null and Undefined in JavaScript · CoreUI
February 9, 2025 - According to the typeof operator, however, typeof null returns 'object'—a quirk dating back to the original JavaScript implementation. If you see null console outputs it indicates a deliberate decision to assign null. This is different from a variable that is simply undefined.