What reason is there to use null instead of undefined in JavaScript?
Asked Answered
K

22

172

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?

Kingsley answered 7/7, 2011 at 1:1 Comment(3)
This is a possible duplicate of stackoverflow.com/questions/461966/…Capsize
Well there are methods like document.getElementById() that can return null but not undefined, so in those cases why would you test the return for undefined? (Sure, it would work if you use == rather than ===, but still, why would you deliberately test for the wrong thing?)Cosmos
It can be helpful to have predictable types and this can guide thinking to use one or another. Where an object is always returned, needed or wanted by design, use null for falsy results (eg document.getElementById('does-not-exist')). Variables var a; and function return values default to undefined. In the past null was in the global scope so using it slowed execution and led me to prefer other falsy types (false, '', 0) to free references. I personally avoid null unless there is a compelling reason otherwise because I perceive it to be simpler, which is generally better.Pharmacology
M
81

null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.

Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.

!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

Moseley answered 3/3, 2015 at 6:58 Comment(22)
I disagree with this. Null is used to define something programmatically empty. Undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a not existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose. Many javascript libraries work like this way.Bail
@Bail What you describe is one of many philosophies. Many js libraries do indeed work that way. Many also don't work that way. In javascript, you can just as easily store an explicit undefined value in an object or array as you can with null. The meanings of both are completely and entirely context dependent. IE they mean what you want them to mean.Moseley
That's why JS is an horrible language. Like you say, many libraries have their own philosophies but you include many libraries for 1 project. So you encounter with many conventions of those libraries. How many times do you need to make different falsy checks. It would not be the last time that you concat a null object to a string and get a "null" as a string. Or passing a 0 as numeric value and wondering why the IF statement handles is t as a false.Bail
@Bail So JS is a horrible language because is has both null and undefined? I can count dozens of bad language decisions in all the major languages, js is no exceptio nthere. I literally never need to or want to use falsy checks in my code and always use === or !==. JS is a fantastically expressive language if you know how to use it.Moseley
@Bail but since properties can be set to undefined, obj.hello !== undefined is not really a safe way to tell if the object contains a hello property. The only safe way is 'hello' in obj. If code behaves differently for null and undefined, I say that's a code smell, because it's hard for developers to be careful and in agreement about such things.Erythroblastosis
@Erythroblastosis I agree, I think having null and undefined and property containment was a bad design choice. Ideally, only one of those would exist (ie setting a property to undefined would mean 'hello' in obj would return false).Moseley
Right. I just learned that the null/undefined dichotomy was necessary because the initial version of JS didn't have hasOwnProperty or the in operator. Now that it does, I don't really understand why one of them didn't get abolished in ES6 or any ES7 proposals I've seen.Erythroblastosis
@Erythroblastosis Two words: legacy code. Like most designs by committee, its backwards compatible to a fault.Moseley
Sure, though they could have a "use superstrict" mode that only allows one of the two :)Erythroblastosis
I completely disagree that null or undefined is unnecessary.Mediatorial
@BT I think its very clear if pr. language have one value describing emptiness, like null in Java or None in Python.For JS using null has not only semantic but also performance purpose, like usage in class faces.Using undefined is required from the way that language designed. For example, Python throws error if you getting non existing property, JS returns undefined.For me is very convenient escape check, if property exists and use undefined if its doesn't.So which one is preferable or which one is bad design ? I think it hardly depends from circumstances and clear answer just doesn't exist.Mediatorial
@Mediatorial This is exactly why my answer says it depends on your conventions in your system. I agree that they're just values that can mean whatever you want them to mean. I would argue tho, that its plenty easy enough to have a semantic value like exports.mySpecialNull1 = {} that you can compare things to - this is just as performant as using null and has far more expressive capability. You can create a whole enum in javascript that you can use in place of basic null vs undefined vs full value. You can go ahead and use null however you want, but there are better alternatives.Moseley
@Andy, I guess as long as JS does not throw an error when you access a non existing attribute, we will have to live with null and undefined. That is to say, they are here to stay :)Seitz
How I have learned it was that NULL is like someones name. You know that anyone has a name, but you don't know her/his name. Undefined is when something didn't exists.Terisateriyaki
this is an opinionated answer and not one with sound backing or insight into the difference between null and undefined and their purposeMahayana
This answer is factually incorrect because it says that null and undefined are values. Null is a value, but undefined is a value type. This fact has consequences, for instance when assigning a default value in destructuring, a null value will overwrite the default, while undefined will not.Bunion
@JordanDavis Undefined is most certainly a value in javascript. That isn't factually incorrect. I won't dispute the differences in handling in various cases, but its incredibly misleading to say that undefined isn't a value that a variable or property or array can hold.Moseley
@Bail you said "If I would make that property intentionally empty, then it must be null so you know that it's on purpose". ... For function input parameters it should make no difference whether a value is empty "on purpose" or "by accident". That sounds like the beginnings of a "footgun".Hyunhz
null == undefined, so you can safely use == (double equals) here. Although that said, it breaks the convention of always using triple equals, and probably requires breaking/turning off linting/code formatting. Usually, nowadays, these situations are probably solved anyway by optional chaining and nullish coalescence. But if I had to choose, I'd say null is for intentional empty values, undefined for unexpectedly empty/absent values.Vorticella
I never have to check if x === undefined or x === null. That's a confusing argument. Are you against both undefined and null? If not, then you must have to check against at least one of them. Otherwise, how do you operate on a value which could be, say, null, or undefined (whichever of it you prefer).Dugald
@Nawaz I clarified, thanks.Moseley
I totally disagree to the statement that one should stop using x == null or x == undefined instead of (x === null || x === undefined) because it makes the code much more readable and has a clear semantics for any serious JS developer.Cordoba
F
117

I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":

When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else. That way, you can explicitly check for the value null to determine if the variable has been filled with an object reference at a later time

Framboise answered 7/7, 2011 at 1:8 Comment(8)
+1 yes, I agree and I always try to remember to initialize vars to null. Then I'm (pretty) sure that undefined means that a disaster happened. Just imho.Nimbus
@Pete - but it tells you nothing about the "disaster", so what's the point? And you can only make that assumption if you know the function follows the convention.Botel
On the other hand, you can also initialize the variable with var myVar; and explicitly check for the value undefined to determine if it has been filled with an object reference at a later time. My point is this is totally academic -- you can do it either way, and anyone who advises one way over the other is simply pushing their own convention.Leong
The only problem I have (since I started with JavaScript 15 years ago) is that you too often have to test undefined and null. This is still really annoying. I avoid assigning a variable to null just to reduce the number of extra null testing.Scallion
@GMan - This is the only place where the == comparison (as opposed to ===) makes sense: v == null (or v == undefined) will check for null or undefined.Pointillism
null is annoying in typescriptPacorro
So should null also be used for a value expecting an Array and not a true JS object?Burchett
The problem with null values is that you have to check both. Is value null or undefined or use ==, but why would you want that?Geest
H
108

At the end of the day, because both null and undefined coerce to the same value (Boolean(undefined) === false && Boolean(null) === false), you can technically use either to get the job done. However, there is right way, IMO.

  1. Leave the usage of undefined to the JavaScript compiler.

    undefined is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables to undefined. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitive undefined.

  2. Only use null if you explicitly want to denote the value of a variable as having "no value".

    As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose.

TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null if and only if you intentionally want a variable to have "no value".


Sidebar: I, personally, avoid explicitly setting anything to undefined (and I haven't come across such a pattern in the many codebases/third party libs I've interacted with). Also, I rarely use null. The only times I use null is when I want to denote the value of an argument to a function as having no value, i.e.,:

function printArguments(a,b) {
  console.log(a,b);
}

printArguments(null, " hello") // logs: null hello
Hipparchus answered 10/1, 2018 at 22:55 Comment(3)
This should have been the selected answerPhallicism
after years of using only undefined and pretending null doesn't exist, I think I am starting to lean towards something like this answerSpatiotemporal
which one to use when you want to clear up MEMORY in high usage applications?Natala
M
81

null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.

Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.

!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

Moseley answered 3/3, 2015 at 6:58 Comment(22)
I disagree with this. Null is used to define something programmatically empty. Undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a not existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose. Many javascript libraries work like this way.Bail
@Bail What you describe is one of many philosophies. Many js libraries do indeed work that way. Many also don't work that way. In javascript, you can just as easily store an explicit undefined value in an object or array as you can with null. The meanings of both are completely and entirely context dependent. IE they mean what you want them to mean.Moseley
That's why JS is an horrible language. Like you say, many libraries have their own philosophies but you include many libraries for 1 project. So you encounter with many conventions of those libraries. How many times do you need to make different falsy checks. It would not be the last time that you concat a null object to a string and get a "null" as a string. Or passing a 0 as numeric value and wondering why the IF statement handles is t as a false.Bail
@Bail So JS is a horrible language because is has both null and undefined? I can count dozens of bad language decisions in all the major languages, js is no exceptio nthere. I literally never need to or want to use falsy checks in my code and always use === or !==. JS is a fantastically expressive language if you know how to use it.Moseley
@Bail but since properties can be set to undefined, obj.hello !== undefined is not really a safe way to tell if the object contains a hello property. The only safe way is 'hello' in obj. If code behaves differently for null and undefined, I say that's a code smell, because it's hard for developers to be careful and in agreement about such things.Erythroblastosis
@Erythroblastosis I agree, I think having null and undefined and property containment was a bad design choice. Ideally, only one of those would exist (ie setting a property to undefined would mean 'hello' in obj would return false).Moseley
Right. I just learned that the null/undefined dichotomy was necessary because the initial version of JS didn't have hasOwnProperty or the in operator. Now that it does, I don't really understand why one of them didn't get abolished in ES6 or any ES7 proposals I've seen.Erythroblastosis
@Erythroblastosis Two words: legacy code. Like most designs by committee, its backwards compatible to a fault.Moseley
Sure, though they could have a "use superstrict" mode that only allows one of the two :)Erythroblastosis
I completely disagree that null or undefined is unnecessary.Mediatorial
@BT I think its very clear if pr. language have one value describing emptiness, like null in Java or None in Python.For JS using null has not only semantic but also performance purpose, like usage in class faces.Using undefined is required from the way that language designed. For example, Python throws error if you getting non existing property, JS returns undefined.For me is very convenient escape check, if property exists and use undefined if its doesn't.So which one is preferable or which one is bad design ? I think it hardly depends from circumstances and clear answer just doesn't exist.Mediatorial
@Mediatorial This is exactly why my answer says it depends on your conventions in your system. I agree that they're just values that can mean whatever you want them to mean. I would argue tho, that its plenty easy enough to have a semantic value like exports.mySpecialNull1 = {} that you can compare things to - this is just as performant as using null and has far more expressive capability. You can create a whole enum in javascript that you can use in place of basic null vs undefined vs full value. You can go ahead and use null however you want, but there are better alternatives.Moseley
@Andy, I guess as long as JS does not throw an error when you access a non existing attribute, we will have to live with null and undefined. That is to say, they are here to stay :)Seitz
How I have learned it was that NULL is like someones name. You know that anyone has a name, but you don't know her/his name. Undefined is when something didn't exists.Terisateriyaki
this is an opinionated answer and not one with sound backing or insight into the difference between null and undefined and their purposeMahayana
This answer is factually incorrect because it says that null and undefined are values. Null is a value, but undefined is a value type. This fact has consequences, for instance when assigning a default value in destructuring, a null value will overwrite the default, while undefined will not.Bunion
@JordanDavis Undefined is most certainly a value in javascript. That isn't factually incorrect. I won't dispute the differences in handling in various cases, but its incredibly misleading to say that undefined isn't a value that a variable or property or array can hold.Moseley
@Bail you said "If I would make that property intentionally empty, then it must be null so you know that it's on purpose". ... For function input parameters it should make no difference whether a value is empty "on purpose" or "by accident". That sounds like the beginnings of a "footgun".Hyunhz
null == undefined, so you can safely use == (double equals) here. Although that said, it breaks the convention of always using triple equals, and probably requires breaking/turning off linting/code formatting. Usually, nowadays, these situations are probably solved anyway by optional chaining and nullish coalescence. But if I had to choose, I'd say null is for intentional empty values, undefined for unexpectedly empty/absent values.Vorticella
I never have to check if x === undefined or x === null. That's a confusing argument. Are you against both undefined and null? If not, then you must have to check against at least one of them. Otherwise, how do you operate on a value which could be, say, null, or undefined (whichever of it you prefer).Dugald
@Nawaz I clarified, thanks.Moseley
I totally disagree to the statement that one should stop using x == null or x == undefined instead of (x === null || x === undefined) because it makes the code much more readable and has a clear semantics for any serious JS developer.Cordoba
S
18

undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.

Sgraffito answered 7/7, 2011 at 1:7 Comment(1)
How do you know if an attempt was made to assign a value, but it failed and undefined was assigned instead?Botel
L
15

Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.

Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar; instead of var myVar = undefined;).

Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.

If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to "" or null because a value of undefined is not considered proper JSON format.

With this said, as a previous poster has expressed, if you find that you're initializing stuff with null or undefined more than once in a blue moon, then maybe you should reconsider how you go about coding your app.

Leong answered 28/10, 2015 at 17:29 Comment(2)
While this is a good stance, I’d like to add this answer: https://mcmap.net/q/20972/-is-it-better-to-return-undefined-or-null-from-a-javascript-functionDaliladalis
@FrederikKrautwald thanks for the link -- that is a very clear delineation.Leong
B
11

You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.

In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?

So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.

Botel answered 7/7, 2011 at 1:58 Comment(0)
S
7

A few have said that it is ok to initialise objects to null. I just wanted to point out that destructuring argument defaults don't work with null. For example:

const test = ({ name } = {}) => {
  console.log(name)
}

test() // logs undefined
test(null) // throws error

This requires performing null checks prior to calling the function which may happen often.

Salespeople answered 17/3, 2019 at 0:52 Comment(2)
This is one of few reasons why i don't use null anywhere in my codebase. often you see something like arg || defaultValue inside the function, if you can provide a default argument then undefined have a superior value... also less codeTrifling
Good point, I guess this is similar to this article medium.com/@hbarcelos/…Headstone
L
3

A useful property in null that undefined does not qualifies:

> null + 3
3
> undefined + 3
NaN

I use null when I want to 'turn off' a numeric value, or to initialize some. My last use was manipulating css transform:

const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });

// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });

Not sure if I should use this property thought...

Logwood answered 27/8, 2016 at 23:37 Comment(0)
K
3

Unknown variable: undefined.

Known variable yet no value: null.

  1. You receive an object from a server, server_object.
  2. You reference server_object.errj. It tells you it’s undefined. That means it doesn’t know what that is.
  3. Now you reference server_object.err. It tells you it’s null. That means you’re referencing a correct variable but it’s empty; therefore no error.

The problem is when you declare a variable name without a value (var hello) js declares that as undefined: this variable doesn’t exist; whereas programmers mostly mean: “I’ve not given it a value yet”, the definition of null.

So the default behavior of a programmer—declaring a variable without a value as nothing—is at odds with js—declaring it as not existing. And besides, !undefined and !null are both true so most programmers treat them as equivalent.

You could of course ensure you always do var hello = null but most won’t litter their code as such to ensure type sanity in a deliberately loosely-typed language, when they and the ! operator treat both undefined and null as equivalent.

Kristinakristine answered 15/8, 2020 at 18:0 Comment(0)
S
2

DOM nodes and elements are not undefined, but may be null.

  • The nextSibling of the last child of an element is null.

  • The previousSibling of the first child is null.

  • A document.getElementById reference is null if the element does not exist in the document.

But in none of these cases is the value undefined; there just is no node there.

Swafford answered 7/7, 2011 at 3:28 Comment(2)
Thanks for the explanation. For me this couldn't be more counter-intuitive.Clique
It really depends on what you're trying to check. For example, if you want to see whether a global variable named 'myVar' exists, then window.myVar would return 'undefined if it doesn't exist. There are tons of stuff that return 'undefined' in JavaScript, just there are tons of things that return 'null' -- it all depends on the context.Leong
P
2

In JavaScript, the value null represents the intentional absence of any object value. null expresses a lack of identification, indicating that a variable points to no object.

The global undefined property represents the primitive value undefined. undefined is a primitive value automatically assigned to variables. undefined is meant to say that the reference is not existing.

Procreate answered 5/2, 2021 at 20:47 Comment(0)
R
2

Based on a recent breakage we ran into, the example below shows why I prefer to use undefined over null, unless there is a specific reason to do otherwise:

function myFunc(myArg) {
    if (typeof myArg === 'string') {
        console.log('a', myArg);
    } else if (typeof myArg === 'object') {
        console.log('b', myArg);
        if (myArg.id) {
           console.log('myArg has an id');
        } else {
           console.log('myArg has an id');
        }
    } else {
        console.log('no value');
    }
}

The following values will play nicely:

'abc'
{}
undefined
{ id: 'xyz' }

On the other hand the assumption of null and undefined being equivalent here breaks the code. The reason being is that null is of type of object, where as undefined is of type undefined. So here the code breaks because you can't test for a member on null.

I have seen a large number of cases with code of similar appearance, where null is just asking for problems:

if (typeof myvar === 'string') {
  console.log(myvar);
} else if (typeof myvar === 'object') {
  console.log(myvar.id);  
}

The fix here would be to explicitly test for null:

if (typeof myvar === 'string') {
  console.log(myvar);
} else if (myvar !== null && typeof myvar === 'object') {
  console.log(myvar.id);  
}

My attitude is to code for the weaknesses of a language and the typical behaviours of programmers of that language, hence the philosophy here of going with 'undefined' bey default.

Ribaldry answered 28/1, 2022 at 17:50 Comment(0)
M
1

I completely disagree that usage null or undefined is unnecessary. undefined is thing which keeping alive whole prototype chaining process. So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.

Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.

var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
    p = new p1();
    if(index > 50000000){
       p.x = "some_string";
    }

    return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)

var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
    p = new p2();
    if(index > 50000000){
       p.x = "some_string";
    }

    return p; 
});
big_array.reduce((sum, p)=> sum + p.value, 0)
Mediatorial answered 23/6, 2016 at 12:6 Comment(1)
undefined holds no special meaning to prototype inheritance. A property set to undefined will still override a property (with the same name) inherited from the prototype.Sedum
O
1

I'm working through this exact question right now, and looking at the following philosophy:

  1. Any function that is intended to return a result should return null if it fails to find a result
  2. Any function that is NOT intended to return a result implicitly returns undefined.

For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.

This answer does not attempt to address:

  1. Property values of null vs undefined
  2. Variables within your functions being null vs undefined

In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).

Orientalism answered 1/7, 2016 at 16:33 Comment(0)
A
1

Here's a reason: var undefined = 1 is legal javascript, but var null = 1 is a syntax error. The difference is that null is a language keyword, while undefined is, for some reason, not.

If your code relies on comparisons to undefined as if it's a keyword (if (foo == undefined) -- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...

Anatollo answered 7/9, 2016 at 0:29 Comment(2)
Use void 0 instead of undefined.Daliladalis
null is a language keyword that estimates a certain value and is usually used to show the absence of a value. Using the typeof operator on null returns the “object”Burhans
F
1

Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.

For example, lodash's get function, which accepts a default value as a 3rd argument:

const user = {
  address: {
    block: null,
    unit: undefined,
  }
}
console.log(_.get(user, 'address.block', 'Default Value')) // prints null
console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value'
console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value'

Another example: If you use defaultProps in React, if a property is passed null, default props are not used because null is interpreted as a defined value. e.g.

class MyComponent extends React.Component {
   static defaultProps = {
      callback: () => {console.log('COMPONENT MOUNTED')},
   }
   componentDidMount() {
      this.props.callback();
   }
}
//in some other component
<MyComponent />   // Console WILL print "COMPONENT MOUNTED"
<MyComponent callback={null}/>   // Console will NOT print "COMPONENT MOUNTED"
<MyComponent callback={undefined}/>   // Console WILL print "COMPONENT MOUNTED"
Fractostratus answered 18/7, 2019 at 8:54 Comment(1)
Don't get me started on null/undefined graphql resolver issues with database nullable columns. Or using things like null in props for something like a classname will end up with 'null' in the .html code and break your css classes.Abebi
A
1

There are already some good answers here but not the one that I was looking for. null and undefined both "technically" do the same thing in terms of both being falsy, but when I read through code and I see a "null" then I'm expecting that it's a user defined null, something was explicitly set to contain no value, if I read through code and see "undefined" then I assume that it's code that was never initialized or assigned by anything. In this way code can communicate to you whether something was caused by uninitialized stuff or null values. Because of that you really shouldn't assign "undefined" manually to something otherwise it messes with the way you (or another developer) can read code. If another developer sees "undefined" they're not going to intuitively assume it's you who made it undefined, they're going to assume it's not been initialized when in fact it was. For me this is the biggest deal, when I read code I want to see what it's telling me, I don't want to guess and figure out if stuff has "actually" been initialized.

Not even to mention that using them in typescript means two different things. Using:

interface Example {
    name?: string
}

Means that name can be undefined or a string, but it can't be null. If you want it null you have to explicitly use:

interface Example {
  name: string | null
}

And even then you'll be forced to initialize it at least with "null".

That's of course only true if you're using "strictNullChecks": true in tsconfig.json.

Abebi answered 13/8, 2021 at 11:36 Comment(0)
T
1

Please note that undefined will be erased if serializing, e.g. with JSON.stringify and is also not visible if using console.log. But it is still there if you debug with Object.keys:

let obj = {nuller: null, undef: undefined}
console.log(obj)
console.log(JSON.stringify(obj))
console.log(JSON.parse(JSON.stringify(obj))
console.log(Object.keys(obj))

And even there if using such things as URLSearchParams

console.log((new URLSearchParams(obj)).toString());

This will print out nuller=null&undef=undefined.

Tillman answered 11/8, 2023 at 13:42 Comment(0)
K
0

To write simple code you need to keep complexity and variation down. When a variable or a property on an object does not have a value it is undefined , and for a value to be null you need to assign it a null value.

Ketosis answered 12/2, 2022 at 4:31 Comment(0)
F
0

Undeclared vs Null

null is both an Object "type" and one of the 7 unique primitive value types called null

undefined is both a global scope property and type called undefined and one of the 7 unique primitive value types called undefined (window.undefined) .

It is the primitive types we use as values we are interested in.

In the case of null, as a value type it means an empty value has been assigned to a variable, but the variable type (Number, String, etc) is still defined. It just has no value. That is what null means. It means a variable has an empty value but it is still a value. It also reinitializes the variable with some kind of value, but is not undefined as a type.

undefined is a special case. When you declare a variable (or use a missing value not yet declared) it is of type undefined, as the browser does not know what type of data has been assigned to it yet. If the variable is declared but not assigned a value is is assigned the primitive calue undefined by default prior to assigning a value, and implies the variable does not exist or exists but has no value assigned.

Like null, undefined is also a primitive value type. But unlike null it means the variable does not exist, where null means the value does not exist. That is why its always better to check if the variable exists and has been assigned a variable using undefined before checking if the value is null or empty. undefined implies no variable or object exists in the compilation at all. The variable has either not been declared or declared with a missing value so not initialized. So checking for undefined is a very good way to avoid many types of errors in JavaScript and supersedes null.

That is why I would not rely on "truthy" checks for true/false with null and undefined, even though they will both return a false response, as undefined implies an additional step for missing feature, object, or variable, not just a true/false check. It implies something more. If you have a missing undeclared variable, truthy statements will trigger an ERROR!

Let's look at undefined first:

        //var check1;// variable doesnt even exist so not assigned to "undefined"
        var check2;// variable declared but not initialized so assigned "undefined"
        var check3 = 'hello world';// variable has a value so not undefined

        console.log('What is undefined?');

        //console.log(check1 === undefined);// ERROR! check1 does not exist yet so not assigned undefined!
        console.log(check2 === undefined);// True
        console.log(check3 === undefined);// False
        console.log(typeof check1 === 'undefined');// True - stops the ERROR!
        console.log(typeof check2 === 'undefined');// True
        console.log(typeof check3 === 'undefined');// False

As you can see undeclared variables, or declared but not initialized, both are assigned a type of undefined. Notice declared variables that are not initialized are assigned a value of undefined, the primitive value type but variables that do not exist are undefined types.

null has nothing to do with missing variables or variables not yet assigned values, as null is still a value. So anything with a null is already declared and initialized. Also notice a variable assigned a null value is actually an object type unlike undefined types. For example...

        var check4 = null;
        var check5 = 'hello world';

        console.log('What is null?');

        console.log(check4 === undefined);// False
        console.log(check5 === undefined);// False
        console.log(typeof check4 === 'undefined');// False
        console.log(typeof check5 === 'undefined');// False
        console.log(typeof check4);// return 'object'
        console.log(typeof check5);// return 'string'

As you can see each act differently and yet both are primitive values you can assign any variable. Just understand they represent different states of variables and objects.

Frentz answered 26/8, 2022 at 5:21 Comment(0)
F
0

There are major differences between null and undefined. If it is used incorrectly, that can have serious consequences. In my example, the owner checks if the product own to the owner or there are no products at all (e.g. in database). With || product === null you can still access the product list even if there is no product record yet. In comparison, with || product === undefined will be not possible

import Product from '../../../models/Product.js';

const checkOwner = async (req) => {
  try {
    const product = await Product.findOne({
      user: req.user.id,
    });
    if (product || product === null) {
      console.log(product ); // print the product OR null
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
    return 'error';
  }
};

export default checkOwner;

And by the way:

null == undefined evaluates true because they are loosely equal.

null === undefined evaluates false because they are NOT equal

Foltz answered 29/9, 2023 at 10:46 Comment(0)
B
0

Null is an object having empty/blank or no value note that null is different than zero because zero has its value is 0;

//null
var d = null;
console.log(d);

Above code null represents the intentional absence of any value and is often used to indicate that a variable has no value or has been explicitly set to null. Assign null to a variable to denote that the variable is declared and initialized and currently doesn't hold a value. Still, a value can be expected in the future.

//undefine
var d; 
console.log(d);

whether undefined is the initial default value of variables. The above code shows variable has been declared but not initialized.

Burhans answered 27/3 at 6:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.