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

前端 未结 14 829
情书的邮戳
情书的邮戳 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: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.

提交回复
热议问题