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

前端 未结 14 787
情书的邮戳
情书的邮戳 2020-11-30 20:28

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 an

相关标签:
14条回答
  • 2020-11-30 21:16

    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.

    0 讨论(0)
  • 2020-11-30 21:17

    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
    
    0 讨论(0)
  • 2020-11-30 21:18

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

    0 讨论(0)
  • 2020-11-30 21:20

    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.

    0 讨论(0)
  • 2020-11-30 21:21

    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.

    0 讨论(0)
  • 2020-11-30 21:22

    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

    0 讨论(0)
提交回复
热议问题