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

前端 未结 14 788
情书的邮戳
情书的邮戳 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
    <MyComponent />   // Console WILL print "COMPONENT MOUNTED"
    <MyComponent callback={null}/>   // Console will NOT print "COMPONENT MOUNTED"
    <MyComponent callback={undefined}/>   // Console WILL print "COMPONENT MOUNTED"
    
    0 讨论(0)
  • 2020-11-30 21:23

    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)
    
    0 讨论(0)
提交回复
热议问题