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

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

    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
       // Console WILL print "COMPONENT MOUNTED"
       // Console will NOT print "COMPONENT MOUNTED"
       // Console WILL print "COMPONENT MOUNTED"
    

提交回复
热议问题