What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

前端 未结 5 1266
囚心锁ツ
囚心锁ツ 2020-11-21 06:25

The \'Wat\' talk for CodeMash 2012 basically points out a few bizarre quirks with Ruby and JavaScript.

I have made a JSFiddle of the results at http://jsfid

5条回答
  •  [愿得一人]
    2020-11-21 06:35

    To buttress what has been shared earlier.

    The underlying cause of this behaviour is partly due to the weakly-typed nature of JavaScript. For example, the expression 1 + “2” is ambiguous since there are two possible interpretations based on the operand types (int, string) and (int int):

    • User intends to concatenate two strings, result: “12”
    • User intends to add two numbers, result: 3

    Thus with varying input types,the output possibilities increase.

    The addition algorithm

    1. Coerce operands to primitive values

    The JavaScript primitives are string, number, null, undefined and boolean (Symbol is coming soon in ES6). Any other value is an object (e.g. arrays, functions and objects). The coercion process for converting objects into primitive values is described thus:

    • If a primitive value is returned when object.valueOf() is invoked, then return this value, otherwise continue

    • If a primitive value is returned when object.toString() is invoked, then return this value, otherwise continue

    • Throw a TypeError

    Note: For date values, the order is to invoke toString before valueOf.

    1. If any operand value is a string, then do a string concatenation

    2. Otherwise, convert both operands to their numeric value and then add these values

    Knowing the various coercion values of types in JavaScript does help to make the confusing outputs clearer. See the coercion table below

    +-----------------+-------------------+---------------+
    | Primitive Value |   String value    | Numeric value |
    +-----------------+-------------------+---------------+
    | null            | “null”            | 0             |
    | undefined       | “undefined”       | NaN           |
    | true            | “true”            | 1             |
    | false           | “false”           | 0             |
    | 123             | “123”             | 123           |
    | []              | “”                | 0             |
    | {}              | “[object Object]” | NaN           |
    +-----------------+-------------------+---------------+
    

    It is also good to know that JavaScript's + operator is left-associative as this determines what the output will be cases involving more than one + operation.

    Leveraging the Thus 1 + "2" will give "12" because any addition involving a string will always default to string concatenation.

    You can read more examples in this blog post (disclaimer I wrote it).

提交回复
热议问题