-1

Similar question answered here: Assign only if condition is true in ternary operator in JavaScript

This is the ternary condition spec from mdn:

condition ? exprIfTrue : exprIfFalse

Often I find myself wanting to check if something is true, but I just want to do nothing with the falsy side of the expression. But I'm not sure how to write this:

(someVariable) ? callFunction(someVariable) : donothing but keep running the script

Should I use 'false', 'null', '', 'undefined' or something else?

The editor gives me an error if I just leave it open without anything to the right of the :

anatolhiman
  • 1,762
  • 2
  • 14
  • 23
  • 2
    The ternary operator is designed for returning values, not for flow control. You must return something. It could be an explicit `undefined` if you like, but again, if that return value is irrelevant, ternaries might not be the right tool. – Nicholas Tower Jan 26 '21 at 03:07
  • 1
    Ternary operator is not merely `cond ? trueValue : falseValue` but `variable = cond ? trueValue : falseValue`. What value is acceptable to set your variable in the false case? Your question is like asking can we just do `var x =` if we don't want to set `x` to any value? The question itself makes no sense – slebetman Jan 26 '21 at 03:13
  • That's useful @NicholasTower I hadn't picked up on that nuance. @slebetman The question in my opinion makes sense if your goal is to check for a null value and do stuff only if the value is truthy. It's not equivalent to your example `var x =` because I clearly do add the exprIfTrue by calling a function (callFunction(someVariable)). The condition is a variable which is truthy or falsy and my example is thus valid as long as I (as Mr. Tower points out) do return something from the falsy side. – anatolhiman Jan 26 '21 at 03:19

3 Answers3

3

might come handy (condition) && (if true -> do this)

Iftekhar
  • 39
  • 1
2

You could use (someCondition) && doifTrue

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND (Short Circuit Evaluation)

freefall
  • 319
  • 1
  • 8
  • Very useful, when searching for your expression I found another answer to the same question, that is well answered here: https://stackoverflow.com/questions/15009194/assign-only-if-condition-is-true-in-ternary-operator-in-javascript – anatolhiman Jan 26 '21 at 04:00
0

Not a ternary. It's a function that the params is ...spreadArr.

let getFuncVal = (...data) => {
  return data.filter(Boolean);
};

console.log(getFuncVal('', 1, 2, 0))
Vince
  • 776
  • 11
  • 21
  • Interesting angle here, but my question regards variables/conditions representing any kind of truthy/falsy value, not only booleans (this may not have been entirely clear, though). – anatolhiman Jan 26 '21 at 04:03