4

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))
silent_coder
  • 6,222
  • 14
  • 47
  • 91

4 Answers4

10

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.

Marius Schulz
  • 15,976
  • 12
  • 63
  • 97
2

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.

hugomg
  • 68,213
  • 24
  • 160
  • 246
1

You can do something like this

This can be shortened with the ?: like so:

var result = a > b ? methodOne() : methodTwo();

methodOne() and methodTwo() can return the result.

hope this will help you.

Zumry Mohamed
  • 9,318
  • 5
  • 46
  • 51
  • the purpose of having such construction is writing less code. I think implement 2 additional methods could be more readable, but much more work. So not sure it fit there – silent_coder Nov 22 '15 at 18:52
1

You can do something like

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

>> var d = {};

>> 2 < 3 ? ((d) => {d.a =2; return d;}) (d) : 5;

>> Object {a: 2}

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60