-1

What is the result of '4' / 2 ?

"4" / 2 = 2

Is it right?

Why this operation is available?

How to can explain this operation?

Author
  • 425
  • 1
  • 4
  • 16

2 Answers2

1

As per the description in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

=== operator can be used in case of comparing value & type both.

For your case, "4" is a string type & 4 is number. So type of "4" & 4 is not equal. Hence "4" === 4 will return false.

Where as if you use == operator which doesn't compare type but values only, will return true. Hence "4" == 4 will return true.

ekta patel
  • 129
  • 3
0

Yes, it is right. / operator converts operands to numbers before calculation. i.e. it implicitly reads a number when a string is passed. So its result is always Number whatever operands are.

From the ECMAScript spec:

11.5 Multiplicative Operators

(...)

1. Let left be the result of evaluating MultiplicativeExpression.

2. Let leftValue be GetValue(left).

3. Let right be the result of evaluating UnaryExpression.

4. Let rightValue be GetValue(right).

5. Let leftNum be ToNumber(leftValue).

6. Let rightNum be ToNumber(rightValue).

7. Return the result of applying the specified operation (*, /, or %) to leftNum and rightNum.

As to "why?", because it is a weakly typed language (Netscape developers designed them to be tolerant about types).

Community
  • 1
  • 1
snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34