4

Why is this even possible?

console.log('13' % 2);

1

I assume JavaScript just converts the string on its own. I would appreciate any info on this behaviour.

SheetJS
  • 22,470
  • 12
  • 65
  • 75
Tomasz Szymanek
  • 253
  • 2
  • 5
  • 15
  • 2
    Whenever a mathematical operation is executed, its operands are coerced into numbers. If either cannot be, the result is `NaN`. If both can be, the operation completes and the value is returned. I think this is the related section in the ES5 spec: http://es5.github.io/#x11.5 . Basically says that `ToNumber` is used on each operand (`ToNumber` is just a pseudo method for what happens internally) – Ian Jun 17 '13 at 03:39
  • @Ian not all mathematical operations (see `+`) – SheetJS Jun 17 '13 at 03:44
  • 1
    @Nirk Well one could argue that if a string is included when using `+`, it isn't a mathematical operation :) But you're absolutely right, that is a great point and I shouldn't have said **all** – Ian Jun 17 '13 at 03:49

1 Answers1

6

As a starting point: http://ecma-international.org/ecma-262/5.1/#sec-11.5

The ToNumber operation is performed on the left argument (which results in the left argument being treated as the number, as explained in http://ecma-international.org/ecma-262/5.1/#sec-9.3.1)

SheetJS
  • 22,470
  • 12
  • 65
  • 75