在javascript中返回falsy值而不是true/false

在javascript中返回falsy值而不是true/false,javascript,ecmascript-6,Javascript,Ecmascript 6,当函数应该返回true或false时,javascript中的最佳实践是什么?我是否可以直接返回falsy值而不是true或false? 我发现这个代码: function supportsAPL(handlerInput) { const supportedInterfaces = handlerInput.requestEnvelope.context.System.device.supportedInterfaces; const aplInterface = supportedI

当函数应该返回true或false时,javascript中的最佳实践是什么?我是否可以直接返回falsy值而不是true或false? 我发现这个代码:

function supportsAPL(handlerInput) {
  const supportedInterfaces = handlerInput.requestEnvelope.context.System.device.supportedInterfaces;
  const aplInterface = supportedInterfaces['Alexa.Presentation.APL'];
  return aplInterface != null && aplInterface !== undefined;
}
function supportsAPL(handlerInput) {
   const {supportedInterfaces} = handlerInput.requestEnvelope.context.System.device;
   return supportedInterfaces['Alexa.Presentation.APL'];
}
并将其简化为以下代码:

function supportsAPL(handlerInput) {
  const supportedInterfaces = handlerInput.requestEnvelope.context.System.device.supportedInterfaces;
  const aplInterface = supportedInterfaces['Alexa.Presentation.APL'];
  return aplInterface != null && aplInterface !== undefined;
}
function supportsAPL(handlerInput) {
   const {supportedInterfaces} = handlerInput.requestEnvelope.context.System.device;
   return supportedInterfaces['Alexa.Presentation.APL'];
}

这是可行的,但我不确定这是正确的/好的javascript。我正在寻找一个有经验的javascript开发人员在找到第一个代码段后会写些什么(同时也希望保存代码行)。

我认为“最佳实践”是始终返回调用方将要使用它的内容。因此,在本例中,函数名为supportsAPL,它似乎应该返回yes/no(
true
/
false
),以让调用者知道您提供的任何输入函数都支持APL或不支持APL

您提到您简化了这一点:

return aplInterface != null && aplInterface !== undefined;
为此:

return supportedInterfaces['Alexa.Presentation.APL'];
在本例中,我们从返回一个特定的true/false变为返回
supportedInterface['Alexa.Presentation.APL'的任何值是。如果支持APL,您将获得
supportedInterface['Alexa.Presentation.APL']的值而如果不支持,则可能会得到一个虚假值
undefined

打电话的人很可能会这样做:

if (supportsAPL(input)) {
    ...
}

但是,如果你只是返回truthy-falsy,你将打破任何期待布尔返回的人。所以这些都不起作用:

if (supportsAPL(input) === true) {
    ...
}

在我看来,在这些场景中总是返回一个布尔值,因为这是函数的要点(以确定输入是否支持APL)

正如@Phil提到的

return aplInterface != null && aplInterface !== undefined;
可以简化为:

return !!supportedInterfaces['Alexa.Presentation.APL']

您可以使用
return!!supportedInterfaces['Alexa.Presentation.APL']
这完全取决于函数调用方的期望值或文档所说的函数将返回的值。如果函数记录了它返回的布尔值,那么它应该返回
true
false
。如果函数记录了它返回的值为任意truthy或false,那么它可以这样做,调用方应该相应地采取行动。如果我在设计一个API,它的主要任务是提供一个布尔结果,我会确保它返回一个实际的布尔值(
true
false
)——任何人都不太可能以最小的代价混淆它。