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

52,229

Solution 1

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 or x === null. 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.

Solution 2

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

Solution 3

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".

I never explicitly set anything to undefined (and I haven't come across this in the many codebases 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

Solution 4

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.

Solution 5

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.

Share:
52,229
Jimmy
Author by

Jimmy

Updated on February 12, 2022

Comments

  • Jimmy
    Jimmy over 2 years

    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?

    • Fatima Mirza
      Fatima Mirza almost 13 years
      This is a possible duplicate of stackoverflow.com/questions/461966/…
    • nnnnnn
      nnnnnn almost 13 years
      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?)
    • jimmont
      jimmont about 8 years
      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.
  • Pete Wilson
    Pete Wilson almost 13 years
    +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.
  • RobG
    RobG almost 13 years
    How do you know if an attempt was made to assign a value, but it failed and undefined was assigned instead?
  • RobG
    RobG almost 13 years
    @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.
  • tomekwi
    tomekwi over 9 years
    Thanks for the explanation. For me this couldn't be more counter-intuitive.
  • thdoan
    thdoan over 8 years
    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.
  • thdoan
    thdoan over 8 years
    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.
  • com2ghz
    com2ghz over 8 years
    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.
  • B T
    B T over 8 years
    @com2ghz 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.
  • com2ghz
    com2ghz over 8 years
    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.
  • B T
    B T over 8 years
    @com2ghz 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.
  • Andy
    Andy about 8 years
    @com2ghz 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.
  • B T
    B T about 8 years
    @Andy 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).
  • Andy
    Andy about 8 years
    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.
  • B T
    B T about 8 years
    @Andy Two words: legacy code. Like most designs by committee, its backwards compatible to a fault.
  • Andy
    Andy about 8 years
    Sure, though they could have a "use superstrict" mode that only allows one of the two :)
  • VahagnNikoghosian
    VahagnNikoghosian almost 8 years
    I completely disagree that null or undefined is unnecessary.
  • Frederik Krautwald
    Frederik Krautwald over 7 years
    Use void 0 instead of undefined.
  • Frederik Krautwald
    Frederik Krautwald over 7 years
    While this is a good stance, I’d like to add this answer: stackoverflow.com/a/37980662/883303
  • thdoan
    thdoan over 7 years
    @FrederikKrautwald thanks for the link -- that is a very clear delineation.
  • VahagnNikoghosian
    VahagnNikoghosian about 7 years
    @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.
  • B T
    B T about 7 years
    @VahagnNikoghosian 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.
  • gwest7
    gwest7 about 7 years
    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.
  • bgusach
    bgusach over 6 years
    @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 :)
  • Rick Love
    Rick Love about 6 years
    @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.
  • Front-end Developer
    Front-end Developer over 5 years
    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.
  • Oscar Gardiazabal
    Oscar Gardiazabal over 5 years
    null is annoying in typescript
  • imbatman
    imbatman about 5 years
    this is an opinionated answer and not one with sound backing or insight into the difference between null and undefined and their purpose
  • Jordan Davis
    Jordan Davis about 5 years
    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.
  • B T
    B T about 5 years
    @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.
  • Matthias
    Matthias over 4 years
    @com2ghz 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".
  • alaboudi
    alaboudi about 4 years
    This should have been the selected answer
  • Victor Zamanian
    Victor Zamanian about 4 years
    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.
  • Matthijs
    Matthijs over 3 years
    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.
  • Endless
    Endless over 3 years
    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 code
  • Dave Cousineau
    Dave Cousineau about 3 years
    after years of using only undefined and pretending null doesn't exist, I think I am starting to lean towards something like this answer
  • Antoni4
    Antoni4 almost 3 years
    Good point, I guess this is similar to this article medium.com/@hbarcelos/…
  • CodeConnoisseur
    CodeConnoisseur over 2 years
    So should null also be used for a value expecting an Array and not a true JS object?
  • CodeXP
    CodeXP over 2 years
    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?