What is the result of the "translate" in JavaScript {}+{}?

Source: Internet
Author: User
Tags add numbers

Original link: What's{} + {} in JavaScript?

Recently, Gary Bernhardt mentioned some interesting javascript tricks in a flash speech called ' Wat '. When you add an object and an object or an array, you get unexpected results. These results will be explained in this article.

In JavaScript, the general rule for + is simple: You can add numbers and strings, and the results will be converted to one of their types. to understand how this type of conversion works, I first need to understand something else. whenever a paragraph is quoted, it is quoted from the ECMA-262 language standard.  

Let's review it together. There are two types of variables in javascript: primitive and reference. primitive types include: null, Undefined, booleans, numbers, and string. The other variables are reference types, including strings and functions.

1. Conversion values

The plus operator behaves as a conversion of 3 types: the conversion to the original value, the number and the string, respectively.

1.1. Convert the variable to the original value by Toprimitive ()

The internal Method toprimitive () is as follows:

Toprimitive (input, Preferredtype?)

the optional parameter preferredtype is a string or a number. It simply expresses a tendency, and the result can be any one of the original values. If Preferredtype is a number type, it will be converted by the following steps:

1. If the input value is a raw value, return it.

2. Otherwise, the input value is an object that calls Obj.valueof (). Returns if the result is the original value .

3. Otherwise, call obj.tostring (). If the result is the original value, return it.

4. Otherwise, throw a type error.

if Preferredtype is a string, step 2 and step 3 are exchanged. If Preferredtype is not specified, the type of the date will be set to string, and the value for other types will be set to number.

1.2 Convert a variable to a number by Tonumber ()

The table below explains how Tonumber converts the original value to number.


1.3 Converting a variable to a string by ToString ()

an object is converted to numbers by calling toprimitive (obj, number), and then Tonumber is called on the resulting primitive result.

The following table explains how ToString () converts the original value to a string.

 

an object is converted to numbers by calling toprimitive (obj, number), and then to the resulting primitive The result is called ToString.

1.4 Trying it out

The following object allows you to observe the transformation process.

var obj = {      function  () {             console.log (' valueOf ');              return  {};       },        function () {              console.log (' toString ');               return  {};       }}

Number is called internally as a function call (not as a constructor) Tonumber ():

>number (obj)

ValueOf

Tostring

Typeerror:cannot Convert object to primitive value  

2. Add

Give the following an addition.

Value1 + value2

In order to evaluate this expression, the following steps are performed:

1. Convert two operands to the original value (mathematical notation, not JavaScript operator)

PRIM1: = toprimitive (value1)

PRIM2: = toprimitive (value2)

The preferredtype parameter is omitted, so for a date type is set to String, For non-date type set to number.

2. If PRIM1 or prim2 are strings, convert them to strings and return The result of the string connection.

3. Otherwise, convert prim1 and prim2 to numbers and return the sum of the results

2.1 Expected results

When you add two arrays, everything will be the same as expected:

[] + []""

converting [] to the original value first tries valueof, and she returns the array itself:

  var arr = [];   = = = Arr  true

The result is not the original value, then the ToString is called and an empty string is returned (this is the original value). Therefore,the result of [] + [] is two empty strings added.

Adding an array and an object also fits our expectations:

  [] + {}  "[Object Object]"

explanation: Converting an empty trend to a string gives the following result.    

"[Object Object]"

So the preceding result is by connecting "" and "[Object Object]".

For more examples, the object is converted to the original value:     

New Number (7)function () {return 2}}function () {return ' def '} }"ABCdef"

2.2 Result of not intention

if the first operand of + is an empty object, things become strange. (as you can see in the console of Firefox)

{} + {}nan  

Why is this so? The problem is that JavaScript interprets the first {} as an empty block of code and ignores it. So nan results are obtained by calculating +{} (plus the second {}). That's what you're looking at . Instead of a binary addition operator, instead of a unary operator, she converts the operand to a number, and the number () is the same. For example:

+ "3.65"3.65

The following expressions are equivalent:

  + {} number  ({})  ///  {}.valueof () is not an original value (   "[Object Object]") )  NaN

Why is the first {} interpreted as an empty block of code? Because the complete input is parsed into a statement and the curly brace is interpreted as the beginning of a block of code at the beginning of the desire. Therefore, you can resolve it by forcing it to become an expression.

({} + {})"[Object Object][object Object]"

The parameters of a function or method are also interpreted as an expression:

Console.log ({} + {})"[Object Object][object Object]"

With the previous explanation, you should no longer be surprised by the following results:

{} + []0

Again, this is interpreted as + []. The following expressions are equivalent:

+//  [].valueof () is not a raw value  0

Interestingly, in the Repl node. js, there is a different explanation for Firefox or Chrome (which is the same as the V8 engine with node. js). The following input is parsed into an expression, and the result a little surprised .

{} + {}"[Object Object][object Object]"+ []"[Object Object]"

It has an advantage that the result is more like an expression as a console.log parameter. But it's not much like using this input as a statement in a program.

3. What is does it all mean?

in most cases, it's not difficult to understand how + works in javascript: You can simply add numbers or strings. The object is converted to a string (if one operand is a string) or a number. If you want to connect two arrays, you need to use a method:

[1, 2].concat ([3, 4]) [1, 2, 3, 4]

there is not an internal method in JavaScript to connect (merge) objects. You need to use a library, such as underscore:

var o1 = {eeny:1, meeny:2}; var o2 = {miny:3, moe:4};_.extend (O1, O2)    1,      2,      3,      4}

Note: Compared to Array.prototype.concat (), extend () changed the first parameter:

O1     1,      2,      3,      43, Moe:4}

If you have a greater interest in operators, you can read this article "Fake operator overloading in JavaScript"

(PS. Translation may have individual errors or inappropriate, also hope to point out, thank you)

What is the result of the "translate" in JavaScript {}+{}?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.