0

Today, I had a typo that was hard to catch because it wasn't throwing an error as I would have expected...

After some quick testing the code below always returns true, and obviously, in this case returns 'first'. Why does this happen? And why doesn't it produce an error?

Here is a simple example of the code:

function func(num) {
  return num = 5 ? 'first' : 'second';
}

console.log(func(1)); // log 'first'

My linter caught it, but I was in a JSBin initially and didn't notice.

omarjmh
  • 13,632
  • 6
  • 34
  • 42

1 Answers1

4

num = 5 ? 'first' : 'second' expression is evaluated as followed:

  1. 5 ? 'first' : 'second' expression is evaluated first (since the conditional operator has higher precedence than an assignment operator) and returns the value 'first' since 5 is "truthy".
  2. num = 'first' expression assigns the 'first' string to the num variable and returns the 'first' since the assignment operator = returns the right operand.

Useful links:

Community
  • 1
  • 1
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • How the hell are you so fast? Thanks for that @zerkms – omarjmh Apr 08 '16 at 02:49
  • 1
    @JordanHendrix I'm a cat - cats are quick :3 – zerkms Apr 08 '16 at 02:50
  • I get the second part, the 5 is truthy, the first part was more the issue, thanks again – omarjmh Apr 08 '16 at 02:51
  • @JordanHendrix yep, check the 1d and 1h items from the second link, it explains how the `=` operator returns the value. – zerkms Apr 08 '16 at 02:51
  • 2
    That's almost but not quite right. num is not assigned 5. It is assigned `'first'`. It is actually evaluated as `5 ? 'first' : 'second'` which evaluates to `'first'`. That is then assigned to num. – RJM Apr 08 '16 at 02:52
  • 2
    @JordanHendrix—ECMAScript follows a precise language specification. Weird is doing an assignment in a return statement, but I guess you know that now. ;-) Very similar to doing `if (x = y)`, which sometimes people actually want, not `if (x == y)`. – RobG Apr 08 '16 at 03:09