在 Javascript 中执行 "functional-style" if-as-expression 是个好主意吗?

Is it a good idea to do "functional-style" if-as-expression in Javascript?

我有一个问题。我通常使用 Kotlin、Rust 和 Elm 等语言编写代码。这些语言有一个特性,可以让我从 if 或 switch 表达式中产生一个值,像这样:

生锈示例:

let x = 10
let biggerThanFive =
  if x > 5 {
    true
  } else {
    false
  }

Kotlin 中的示例:

val x = 10
val biggerThanFive =
  if (x > 5) {
    true
  } else {
    false
  } 

现在 Javascript,我很少偶然发现使用 if 作为表达式的代码(我通常在匿名函数和箭头函数的帮助下使用它)

const x = 10
const biggerThanFive = (() => {
  if(x > 5) {
    return true
  }
  else {
    return false
  }
})()

相反,通常是这样

const x = 10
let biggerThanFive

if(x > 5) {
  biggerThanFive = true
}
else {
  biggerThanFive = false
}

有什么理由在Javascript中使用if-as-expression技术吗?

为什么不直接用表达式呢?

const
    x = 10,
    biggerThanFive = x > 5;

如果你需要 return 只是 true 或 false,你可以将表达式直接放入赋值中。

const x = 10;
const biggerThanFive = x > 5;

但是,如果你想return其他基于条件的结果,你可以试试条件三元运算符。

const x = 10;
const biggerThanFive = x > 5 ? "Return when it's true" : "Return when it's false";

更多信息您可以查阅文档:Conditional (ternary) operator

你写的代码不是那么实用,那里挂着不纯的 x:

const x = 10
const biggerThanFive = (() => {
  if(x > 5) {
    return true
  }
  else {
    return false
  }
})()

另外,立即执行的匿名函数是不合常理的,读起来超级混乱。

如果我想快速比较函数式风格和 javascript,我会这样做:

const biggerThanFive = _in => _in > 5
const isBigger = biggerThanFive(10)

如果我发现自己经常这样做,我可能会引入一个实用函数,让我可以这样做:

const isTrue = (fn, _in) => fn(_in)
const res = isTrue(_in => _in>5, 19)

这样我就可以避免为匿名函数命名或显式调用它。