Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ternary operator (?:) change and return object in single block

Tags:

javascript

Is it possible inside ?: change dictionary and return this dictionary in the same block. Something like this a > b ? <dict['c'] = 'I'm changed', return dict> : <some other code>;

I need this inside map function. Something like this:

var a = [...]
a.map((itm) => return itm.isComposite ? itm[key] = transform(itm[data]); return itm : transform(itm))
like image 678
silent_coder Avatar asked Dec 09 '22 00:12

silent_coder


2 Answers

Yes, it's possible by using the comma operator:

a > b ? (dict['c'] = "I'm changed", dict) : <some other code>;

The comma operator evaluates all of its operands and returns the value of the last (rightmost) one.


However, a proper if statement might be the more readable solution here, which is why I'd recommend you use it instead of constructing a conditional ("ternary") expression.

like image 53
Marius Schulz Avatar answered Dec 11 '22 12:12

Marius Schulz


The comma operator should be enough. No need to use the return keyword.

var result = (a > b
  ? (dict['c'] = "I'm changed", dict)
  : <some other code> );

If you want to return the result then it goes outside the expression:

return (a > b
  ? (dict['c'] = "I'm changed", dict)
  : <some other code> );

That said, I would prefer using if statements for this problem. In my opinion, long ternary expressions are hard to read.

like image 37
hugomg Avatar answered Dec 11 '22 12:12

hugomg