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

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

提交回复
热议问题