传递空参数 null 或 undefined 哪个更可靠? (同时期待一个功能)

which is more reliable for passing empty argument, null or undefined? (while expecting a function)

If we’re interested only in errors, then we can use null as the first argument: .then(null, errorHandlingFunction). Or we can use .catch(errorHandlingFunction), which is exactly the same:

from javascript.info


当我们想将第一个参数作为空参数传递时,nullundefined 之间有什么区别吗?我认为 undefined 更方便,因为当我们调用一个不带任何参数的函数时,所有参数都将是 undefined。那么什么是最好的,为什么?

谢谢

编辑: 例如

.then(null, errorHandlingFunction)
//or
.then(undefined, errorHandlingFunction)

但我问的不是通用目的 .then()

编辑2:非常有趣。 Stack Overflow 管理员将此问题标记为“基于意见”。那我该怎么办?我只想要其他人对一般用法有可靠理由的意见,而不是特定的代码片段。

有了.then,没关系。如果第一个参数不可调用,那么无论它的值是多少,它都将被完全忽略。见 specification:

  1. If IsCallable(onFulfilled) is false, then

a. Let onFulfilledJobCallback be empty.

所以你也可以 .then(123, errorHandlingFunction)

但是,如果您根本不打算将 onFulfilled 回调作为第一个参数传递,则使用 .then 没有任何意义 - 您应该改用 .catch

.catch(errorHandlingFunction)

完全等同于

.then(somethingNotCallable, errorHandlingFunction)

只是它在语义上更正确且更易于阅读。

But I asked general purpose not only for .then()

由你决定;你可以指定你想要的逻辑,函数的用户必须遵守它。

需要注意的一点是,如果使用undefined作为参数,可以使用默认参数,但如果传递null,则不会使用默认参数:

const fn = (someArg = 5) => {
  console.log(someArg);
};

fn(null);
fn(undefined);