Some understanding of JS = = operation

Source: Internet
Author: User

Disclaimer: This article is excerpted from an article, put on this only for a note to be able to learn better.

Big Home knows, = = is a more complex operator in JavaScript. Its operational rules are strange, making it easy to make mistakes, and become one of the "worst features" in JavaScript.

After carefully reading the ECMAScript specification, draw a picture, through which you will thoroughly understand everything about = =. At the same time, trying to prove by this article = = is not so bad things, it is easy to grasp, even seems reasonable.

First:

Figure 1 Graphical representation of the = = Operation rule

The exact description of the arithmetic rule is here: the Abstract equality Comparison algorithm (http://es5.github.io/#x11.9.3). But, with such a complicated description, are you sure your brain won't faint after reading it? Sure you'll be able to guide the practice immediately?

Certainly not, specifications are for developers of JavaScript running environments (such as developers of V8 engines), rather than for language users. And it is the complex description of the specification translated into a more easily understood form.

Before we go into each of the sections in Figure 1, let's review the information about the types in JS:

    1. There are two types of values in JS: Primitive types (Primitive), Object Types (objects).

    2. The original types are: Undefined, Null, Boolean, number, and string.

    3. Both the undefined type and the null type have only one value, that is, the undefined and Null;boolean types have two values: the value of true and the False;number type is many, and the value of the string type is theoretically numerous.

    4. All objects have the valueof () and ToString () methods, which inherit from object and, of course, may be overridden by a quilt class.

Now consider an expression:

x == y

where x and y are the values of one of the six types above.

When x and y are of the same type, x = = y can be converted to x = = y, while the latter is very simple (the only thing to be aware of is Nan), so let's consider the different types of x and Y.

1 with and without

In Figure 1, the six types of JavaScript values are represented by a rectangle with a blue background. They were first divided into two groups:

    • String, Number, Boolean, and object (corresponding to the large rectangular box on the left)

    • Undefined and null (corresponds to the rectangular box to the right)

What is the basis of grouping? Let's take a look at the right side of the undefined and null is used to denote indeterminate, none , or null , while the four types on the right are deterministic , both with and not NULL . We can say this:

On the left is a world of existence , and on the right is an empty world.

Therefore, it is reasonable to compare the results of any values in the left and right worlds to do = =. (See Figure 1 for the two-rectangle horizontal line labeled false)

2 Empty and empty

Undefined and null in JavaScript are another place that often crashes us. Often it is considered a design flaw, which we do not delve into. But I have heard that the author of JavaScript originally thought:

If you are going to assign a variable to the value of the object type, but you do not have an assignment yet, you can use NULL to indicate the state at this point (one of the evidences is that the result of typeof null is ' object '); Conversely, if you are going to assign a variable to the value of the original type, but there is no value assigned, Then you can use undefined to represent the state at this time.

Whether or not this rumor is credible, the result of both doing = = Comparison is true is quite reasonable. (See true on the right vertical line in Figure 1)

Before proceeding to the next step, let's start with the two symbols in 11: Capital letters N and P. These two symbols are not the positive and negative meanings of PN junctions. But:

    • n represents the Tonumber operation, which turns the operand into a number. It is an abstract operation in the specification, but we can use the number () function in JS as the equivalent substitution.

    • P represents the toprimitive operation, which shifts the operand to the value of the original type. It is also an abstract operation in the specification and can be translated into equivalent JS code. But slightly more complicated, simply put, for an object obj:

Toprimitive (obj) is equivalent to: computes the obj.valueof () first, returns this result if the result is the original value, otherwise, evaluates obj.tostring (), returns the result if the result is the original value, or throws an exception.

Note: Here is an exception, the date type object, which calls the ToString () method before calling the ValueOf () method.

In Figure 1, a line labeled N or P indicates that when the two types of data it is connected to do a = = operation, the operand marked with the side of N or P performs the Tonumber or toprimitive transformation first.

3 True and False

As you can see from Figure 1, when the Boolean value is compared to other types of values, the Boolean value is converted to a number, specifically


1false -> 0

There is no need to waste too much of your breath. Think about it. In C, there is no Boolean type at all, which is usually used to indicate that the logic is true or false in integers 1 and 0.

Sequence of 4 characters

In Figure 1, we divide the string and number types into a group. Why is it? Of the six types, both string and number are sequences of characters (at least literally). A string is a sequence of all valid characters, and a number can be seen as a sequence of characters that match a particular condition. Therefore, a number can be considered a subset of a string.

According to Figure 1, the string and the number do = = operation, you need to use the Tonumber operation, the string into a number. Suppose X is a string and Y is a number, then:

x == y -> Number(x) == y

So what are the rules for converting strings into numbers? The specification is very complex, but roughly speaking, it is to remove the whitespace characters on either side of the string, and then remove the quotes on both sides to see if it can form a valid number. If so, the result is this number; otherwise, the result is Nan. For example:

Number(‘123‘) // 结果123
Number(‘1.2e3‘) // 结果1200
Number(‘123abc‘) // 结果NaN
Number(‘\r\n\t123\v\f‘) // 结果123

Of course there are exceptions, such as the result of converting a blank string to a number is 0. That

Number(‘‘) // 结果0Number(‘\r\n\t \v\f‘) // 结果0
5 Simplicity and complexity

Primitive types are simple types that are straightforward and easy to understand. However, the disadvantage is that the ability to express is limited, it is difficult to expand, so there are objects. An object is a collection of properties, and the property itself can be an object. So objects can be arbitrarily complex enough to represent a variety of things.

But sometimes things are too complicated to be good. For example, a lengthy paper, not everyone has the time, patience or need to read from beginning to end, usually only understand the central idea is enough. So the paper has a keyword, an overview. The object in JavaScript is the same, we need a way to understand its main features, so the object has the ToString () and valueof () methods.

The ToString () method is used to get a textual description of the object, whereas the valueof () method is used to get the eigenvalues of the object.

Of course, it's just my own understanding. As the name implies, the toString () method tends to return a string. So what about the valueof () method? According to the specification, it tends to return a number--even though the built-in type, the ValueOf () method returns numbers with only number and date.

According to Figure 1, when an object is compared to a non-object, the object needs to be converted to the original type (although when compared to a Boolean type, it is necessary to turn the Boolean type into a numeric type, but then the object type becomes the original type). This is also reasonable, after all, = = is not a strict equality comparison, we only need to take out the main characteristics of the object to participate in the operation, the secondary features on the side of the line.

6 All things are counted

We looked back at 11. There are no directions for the lines labeled N or P. If we put an arrow on these lines so that the connection points to the other end of the line labeled N or P, we get (regardless of undefined and null):

7 for an example

Too much nonsense, here or an example, to prove that figure 1 is indeed convenient and effective to guide the practice.

example, calculate the value of the following expression:

[‘‘] == false

First, the two operands are object type, Boolean type, respectively. According to Figure 1, the Boolean type needs to be converted to a numeric type, and false to a number results in 0, so the expression becomes:

[‘‘] == 0

Two operands become object type, number type. According to Figure 1, the object type needs to be converted to the original type:

    • First Call [].valueof (), because the array's valueOf () method returns itself, so the result is not the original type, continue to call [].tostring ().

    • For arrays, the ToString () method is an algorithm that converts each element to a string type and then joins with a comma ', ' in turn, so the end result is an empty string ', which is a value of the original type.

At this point, the expression becomes:

‘‘ == 0

Two operands become string type, numeric type. According to Figure 1, you need to convert the string type to a numeric type, which says that the empty string becomes a number 0. The expression then becomes:

0 == 0

At this end, the type of the two operands is finally the same, and the result is obviously true.

As you can see from this example, you need to remember the rules for the ToString () and valueof () methods of the built-in objects, in addition to remembering Figure 1, to master the rules of the = = operation. Including object, Array, Date, Number, String, Boolean, and so on, fortunately this is not difficult.

8 Deformation again

Actually, figure one is not perfect enough. Why is it? Because objects are transformed by objects when compared to strings/numbers, Boolean types are required to be compared with Boolean types that are also primitive types. In fact, just a little bit of analysis, it is also equivalent to all of the objects being converted to the original type. So we got the final more perfect graphics:

Figure 3 graphical representation of the more perfect = = Arithmetic rule

There is one place that might confuse you: Why is a Boolean and string labeled with two n? Although the rule should be changed from Boolean to number, the next string is going to be a number, so it's better to turn it into a number at the same time.

9 Summary

In front of the mess, according to the final Figure 3 we get, we summarize the rules of the = = Operation:

    • undefined = = NULL, the result is true. And the result of comparing them to all other values is false.

    • String = = Boolean, which requires two operands to be converted to number at the same time.

    • String/boolean = =number, need String/boolean to number.

    • Object = = Primitive, requires object to Primitive (specifically through the valueOf and toString methods).

See, there are only 4 rules ! is not very clear, very simple.

Some understanding of JS = = operation

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.