-3

Check the code Image

How I am getting Output = 1 for console.log('6'/'6') in Javascript. It should not be able to devide two strings

  • 1
    Why shouldn't it be able to? Why would you be dividing two strings in the first place? What would be your goal, if not to divide them? So what else would you expect? An error throwing? – GoldenretriverYT Jan 26 '22 at 07:30
  • https://www.geeksforgeeks.org/what-is-type-coercion-in-javascript/#:~:text=Type%20Coercion%20refers%20to%20the,are%20applied%20to%20the%20values. – Brendan Bond Jan 26 '22 at 07:30

1 Answers1

2

When a mathematical operator that only makes sense on numbers is applied to two expressions, both expressions are coerced to numbers first..

4. Let lnum be ? ToNumeric(lval).
5. Let rnum be ? ToNumeric(rval).
7. 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
...

which then calls Number::divide with lnum and rnum.

The only exception is +, which will only add if both sides are numbers - otherwise, it will coerce both sides to strings and then concatenate.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320