What exactly is Type Coercion in Javascript?

前端 未结 10 1112
后悔当初
后悔当初 2020-11-22 04:36

What exactly is type coercion in Javascript?

For example, on the use of == instead of ===?

10条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:29

    In Python if you try to add, say, strings and integers, you get an error:

    >>> "hi" + 10
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: cannot concatenate 'str' and 'int' objects
    

    Yet in JavaScript, you don't. The 10 gets converted to a string:

    > "hi" + 10
    "hi10"
    

    "Type coercion" is just a fancy misnomer for the above. In actuality, neither language has "types" in the sense of Java or C or other languages with static type systems. How the languages treat interactions between the various non-statically-typed values is a matter of choice and convention.

提交回复
热议问题