1

I'm struggling to understand how to evaluate this expression +!!NaN * "" - - [,]

Can anyone help me please?

  • [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) – VLAZ Aug 03 '21 at 12:53
  • @VLAZ mixed with JS quirks :) – Robo Robok Aug 03 '21 at 12:54
  • @RoboRobok barely any. Just some conversions. Re-write it to a proper form and it's not that hard to follow. – VLAZ Aug 03 '21 at 12:54
  • 3
    Expand each expression tree on the right panel: https://astexplorer.net/#/gist/1ec8a5d88c2d575263aa9046c6c73db9/febcc9acc5155bd7ecab6610f359197b24459820 – adiga Aug 03 '21 at 12:57
  • @VLAZ multiplying number by string is not a quirk? – Robo Robok Aug 03 '21 at 12:59
  • @RoboRobok multiplication always converts both operands to numbers. So, barely a quirk. `s * 1` is a trick that is somewhat popular to convert strings to numbers. – VLAZ Aug 03 '21 at 13:00
  • 1
    I have never seen any professional code doing that, that's awful. I wish JS threw errors in cases like that instead of doing some random hocus-pocus. – Robo Robok Aug 03 '21 at 13:04
  • 1
    @RoboRobok I didn't say it's a *good* practice. Just that it's somewhat popular. A unary plus or using `Number` is much better. – VLAZ Aug 03 '21 at 13:05
  • Yeah, my preferred way is definitely `Number(s)`. But it's interesting I haven't seen this popular way in my almost 20 years with JS. – Robo Robok Aug 03 '21 at 13:07
  • @RoboRobok https://stackoverflow.com/a/43056963 https://stackoverflow.com/a/22440945 https://stackabuse.com/javascript-convert-string-to-number just some of the first results I found for "convert string to number javascript" – VLAZ Aug 03 '21 at 13:09

1 Answers1

0
+!!NaN; // !NaN => true -> !true => false -> +false => 0


Number(""); // -> 0

-[,]; // -> - 0 , [,] is empty so it will be casted to 0

Add it all together:

0 * 0 - -0; // -> 0
Dharman
  • 30,962
  • 25
  • 85
  • 135
Zouhair Dre
  • 558
  • 4
  • 14