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

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

提交回复
热议问题