What exactly is Type Coercion in Javascript?

前端 未结 10 1132
后悔当初
后悔当初 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:33

    Type coercion is the process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion. To recall, primitives are: number, string, boolean, null, undefined + Symbol (added in ES6).

    Type coercion can be explicit and implicit.

    When a developer expresses the intention to convert between types by writing the appropriate code, like Number(value), it’s called explicit type coercion (or type casting).

    Since JavaScript is a weakly-typed language, values can also be converted between different types automatically, and it is called implicit type coercion. It usually happens when you apply operators to values of different types, like 1 == null, 2/’5', null + new Date(), or it can be triggered by the surrounding context, like with if (value) {…}, where value is coerced to boolean.

    here is some example for implicit type coercion:

    true + false
    12 / "6"
    "number" + 15 + 3
    15 + 3 + "number"
    [1] > null
    "foo" + + "bar"
    'true' == true
    false == 'false'
    null == ''
    !!"false" == !!"true"
    [‘x’] == ‘x’
    [] + null + 1
    [1,2,3] == [1,2,3]
    {}+[]+{}+[1]
    !+[]+[]+![]
    new Date(0) - 0
    new Date(0) + 0
    

    read more: https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/

提交回复
热议问题