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

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

    I'm working through this exact question right now, and looking at the following philosophy:

    1. Any function that is intended to return a result should return null if it fails to find a result
    2. Any function that is NOT intended to return a result implicitly returns undefined.

    For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.

    This answer does not attempt to address:

    1. Property values of null vs undefined
    2. Variables within your functions being null vs undefined

    In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).

提交回复
热议问题