Nowadays, all kinds of frameworks and tools “run amok”, everywhere in the principle and source code, more cross-end technology needs us to explore, but if the basic skills are not good, learn what is half the effort, the effect is very bad, take time at the same time to blow confidence. This article, the fourth in the series of “Light talk front end” planned by me, aims to systematically and logically share the knowledge of native JavaScript with you, helping you to easily understand and memorize the knowledge system, and I will do my best to live up to expectations.

Where there is data involved and a result is called operation – inspiration

In this series of articles, it is time to talk about arithmetic. After talking about variables and objects, it is time to talk about arithmetic. As mentioned above, programs are all about “data storage” and “data processing”.

Four Operations (besides)

Speaking of operation, have to reminiscent of mathematics, the most familiar with is “add, subtract, multiply and divide” arithmetic, you can think of, also have these operations of JavaScript, because of numeric types, but it is far more than these four, and in terms of these four, like in mathematics is not entirely, in some scenarios, “magic happens”. Why is that? Remember, as a computer, you’re going to have to react to any line of code, any character that’s given to you, and JavaScript in particular, which is dynamically weakly typed, is pretty tolerant of reacting as much as you can without knowing what the variables are.

Leave the “magic transformation” for now, and let’s look at what else it does.

Two unary

What is two-yuan? “yuan” is the number of data involved in the operation. Two-yuan means there are two data involved in the operation.

Equal/not equal to (exactly)

It’s easy to start with equals, but it takes novice programmers a while to get used to the idea that JavaScript equals is different from math in that it requires the “==” symbol instead of the “=” symbol, which in JavaScript stands for “assignment.”

if(a = 3){
}
Copy the code

This is assigning 3 to A, not determining whether the two are equal, so be careful.

In addition, there is only equal, greater than, less than and so on in mathematics, but there is no “not equal”, and the program adds “not equal”, which can unify the two cases with one operation. It is written as follows:

a! =bCopy the code

Functionally, this is fine, but it’s not safe, because browsers will try to cast a little bit of equality and then compare it. Such as

0 == "//true" null == undefined //trueCopy the code

The 0 and space characters are obviously two different concepts, and null and undefined are not the same. Cannot be declared equal, but returns true, so it is recommended to use the “complete operator” when determining whether two values are equal. The following is an example:

0 === '//false null === undefined //falseCopy the code

The complete operator checks the type at the same time as the comparison. Not at all! = = “.

So we can determine exactly what it is.

Modulo (remainder)

In contrast, the modulus (%) operation is less common, and it does something like this:

let result = 55 % 10; / / 5Copy the code

See if they’re divisible, and if they’re not, you get the remainder.

The application scenarios are as follows: Check whether a number is an integer multiple (for its own purpose). Based on this function, you can check whether a number is an integer multiple of 2, and then check whether the number is odd or even.

index

In the past, we used the poW method for Math objects to raise a number to the power mentioned in the previous article:

Let the result = math.h pow (3, 2); / / 9Copy the code

ES7 has since introduced a new operator, **, which can be written as follows.

let result = 3**2;
Copy the code

It’s more concise in writing.

The assignment

We said that “=” is assignment, but there are a number of other simplified ways to write assignment after an operation. The uniform expression is: variable operator = variable (constant).

That is, you perform an operation on a variable and then you assign the value to the original variable. The following is an example:

a += 1; // a = a+1; a *= 1; a /= 1; A % = 2;Copy the code

Logical operations

What is logic? The result of a logical operation in JavaScript is “true/false”, “yes/no”, which determines whether a condition is true or not.

“&&” — and operation, are true, the result is true.

The most intuitive:

let result = true && false;  //false
Copy the code

But normally you don’t manipulate booleans this directly, you use the results of other operations. Such as:

let a = 4;
let result = a > 3 && a < 5;  // true
Copy the code

“| | – or” operation, there is a true is true, otherwise is false.

let a = 4;
let result1 = a < 3 || a > 5; // false
let result2 = a > 3 || a > 5; // true
let result3 = a > 3 || a < 5;  // true
Copy the code

These two operators for many scenes of daily development provides a convenient way of judgment, commonly used in process control conditions in judgment, but sometimes will be around in, for example, when you need a and b two scenarios are applicable, may be because of this “and” word, instinctively chose “and” operation, namely “&”, this is wrong, All applicable meaning is “a” or “b”, want to use “| |”.

In addition, logical operators can be used not only to get “yes” or “no”, but also in a common use called “short-circuiting”.

Let’s start with some code:

let result;

if(a){
   result = b
} else {
   result = a
}

if(a){
    result = a;
} else {
    result = b;
}
Copy the code

In the first case, result gets B if a has a value and is not false(including implicit casts), otherwise it gets A.

In the second case, when a has a value and is not false (including casting), we can’t look further, result gets a, otherwise we get B.

But the above method is a little tedious, if using “short circuit operation”, can be like the following:

let result = a && b;
let result = a || b;
Copy the code

The effect is the same.

The short circuit notation gives us the “priority” of the assignment. The logic doesn’t change, just the assignment.

So, when we want to choose between two values, we can consider using “short-circuit algorithm”, one line of code, concise, clear.

unary

I’m going to say two because two is familiar and easy to accept, unary is easy to understand, one operator, one operand.

+/-

“+” and “-” can be used as unary as well as as binary operators, and the most common is “positive and negative”.

+ 1 to 1Copy the code

However, it makes a difference if you put it not directly before a number, but before a variable.

Such as:

let a = '1'; let result = +a; // 1 let result = -a; / / 1Copy the code

In this code, a is originally the string “1”, after adding a “+” or “-“, it becomes a number. Why? Because it doesn’t make sense to prefix a string with a sign that represents “plus or minus”, JavaScript tries to make sense of it.

Note that the word “attempt” is not always successful. If the value cannot be converted to a number, it will fail.

let a = 'a';
+a  //NaN
Copy the code

Although unary operators do have this function, they are implicit conversions. They are only used when the type of the received value does not match that of the desired value. If you are sure of your operation and the code is legible, you can use the Number() method to perform explicit conversions.

++/–

Two are called “increment” or “decrement” because there is no other data to combine with it, and because there is no data to combine with it, it can only “increment” or “decrement” 1 each time.

A ++ // increases by 1 a-- // decreases by 1Copy the code

The function is simple, but the position that puts had pay attention to, put before put have distinction after.

let result = a++; // let result = ++a; // the symbol precedes the increment before the assignmentCopy the code

These two operators are often used in code segments that need to be repeated, reach a critical value after several operations, and then proceed with other operations or stop operations, the most common being the for loop.

for(let i = 0; i<=length; I++){// perform the operation}Copy the code

In each loop, I increases by 1 until length is reached and stops.

!

“!” It’s called the “invert” operator, and it’s supposed to be a logical operation, and it inverts the value of the result, and the result is true, and the result is false, and the result is false, and the inverse is true.

let a = false; if(! A){// the operation performed when a is false, which includes not only false but also other values that can be Boolean converted to false}Copy the code

You can use “! “whenever you want. Operator. A common scenario is state switching.

let on = true; function changeStatus(){ on =! on; }Copy the code

Bind a click event to the element whose state you want to switch, and then execute changeStatus, which changes to the opposite value each time you click, to achieve the effect of repeatedly clicking the state.

The ternary operation

Ternary operation, also called “conditional operation”. Ternary operators are also common in JavaScript. The format is as follows:

Expression? Value 1: Value 2

Example:

let a = 3; let result = a>2? True: false;Copy the code

What this code says is, if a is greater than 2, take the first value, otherwise take the second value. That is, the value is determined by whether the expression is true or not.

The operation and talking in front of the “| |” the effect of the operation has a similar place, you can choose to use according to the concrete situation.

Points to be aware of

+ connectivity

We’re used to using “+” to add numbers, but in JavaScript, another common use of “+” is “concatenate strings.” As follows:

let result = 'a'+'b';   // "ab"
Copy the code

Although strings themselves have concatenation methods, “+” is more direct and concise.

But if that’s all there is to it, then there’s nothing to notice, and the biggest uncertainty in the JavaScript world is what variable you get.

If so:

let result = 1 + 'b';
Copy the code

What do I get when I add numbers and strings? Is “1 b”.

And you might say, well, that’s b, because you can’t convert it to a number. Let’s switch:

let result = 1 + '2';
Copy the code

The answer is “12”, which is obviously wrong.

When a binary operation is performed using the + sign, the result is a string if the data on either side is a string or is converted to a string. Such as:

let result = "";
result + 2  //"2"
result + undefined  // "undefined"  
result + null   //  "null"
Copy the code

Why single out “+”? Because only “+” has this special function, other operators do not.

String comparison

In business requirements, where a set of data is often sorted by size, there is a trap waiting for us — string comparisons.

There are two algorithms for string comparison:

  • Bit by bit until you get the result
  • ASCII code values are compared

Such an algorithm would appear as follows:

100 < 20   //true
Copy the code

In fact, this is not true, and I’m doing this on purpose, because sometimes, when you look at numbers, maybe it’s a string, maybe you’re comparing “100” and “20”, that’s what happens.

The charCodeAt() method is used to view the ASCII code values of the characters, where ‘1’ is 49 and ‘2’ is 50. We’ve already sorted it out by comparing the first one.

Here’s another example:

'13' > '123'   //true
Copy the code

The first digit 1 is equal, and the second digit 3 is larger than the ASCII digit 2.

Therefore, when sorting data, it is important to pay attention to the type, otherwise it may not be consistent with the expected, such as numbers, letters or other special symbols, not to repeat.

An implicit conversion of objects

It’s time for the interview questions

Ask “Under what circumstances is it true that a == 1&&a == 2&&a == 3? “

This is… It seems irrational. Isn’t that a trick?

Now, hold on, let’s talk about something I haven’t mentioned so far. I’ve been saying that primitive types are converted, not objects.

Comparing a value to an object may seem unuseful, but the program is still allowed to run, and there are mechanisms for handling it.

Object to number and string conversions are directly related to valueOf() and toString() methods. Here are the rules:

  • If you try to convert to a string, try the toString() method first, then the valueOf() method.

  • Otherwise, try calling the valueOf() method first and then toString().

Some people ask, where did these two methods come from? Remember from the last article? They are built-in methods from prototypes.

So the above question found a way to make it work:

let a = { i: 1, valueOf: function () { return a.i++; }} the if (a = = 1 & & & & a = = a = = 2 3) {the console. The log (' I came true! '); } // I am real!Copy the code

We can take advantage of the fact that the valueOf (or toString) method is called when the type is converted, and we can just write the other effects we want inside.

Understand this truth, is not afraid of a little?

Of course, this problem is not only this kind of plan, just another kind of plan slightly off the subject, we will talk about the object later when digging ~

conclusion

In JavaScript, there are more or less operations, especially the processing mechanism of implicit type conversion, which requires more experience accumulation.

For space reasons, the infrequent and some details are omitted here, but in either case, can be summarized as two:

  • Values: Mathematical calculations, string concatenation, or even “short-circuit algorithms” are all designed to get a value, and when a valid value cannot be obtained, an unexpected result such as NaN or an error is returned.
  • Logic judgment: use “&&, | |,!” Or the case of implicit transformation, as a conditional judgment of process control.

In this way, we only need to care about what we have to do, every unexpected situation to write down, and gradually everything will be clear.

After variables (value storage), object systems (programming soil), and operations (how data is processed), it’s time to break down the different types.

See you next ~

Blog link: [talking about the front end] those “unreasonable value” operations

Series of articles:

【 Talk about the front end 】 good basic skills, easy to learn with me

Small role, big use — variable

Why is everything an object?