Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Is it always possible to see a variety of JS optimization, JS skills, in fact, the principle is in these basic knowledge you know? 🧐

Ask questions

PS: The answers are all in the text

What is the result of 👉 1++?

What is the result of 👉 1 | | 0?

👉 do you know short circuit evaluation?

👉 about | | (or), && (with),! (non), null value merge operator ‘?? ‘priority?

👉 Previous review: Mathematical operators in JavaScript

The campaign needs to collect 🥂 [10 comments] 🥂, the current progress is still zero 😭, so




Increase/decrease automatically

🎨 example:

let counter = 2; counter++; // same as counter = counter + 1 counter--; // same as counter = counter - 1Copy the code

💥 Note: Increment/decrement can only be applied to variables, and an error will be reported if applied directly to numbers




Logical operator

JavaScript has three logical operators: | | (or), && (with),! (a).

||(or) + expand

If any of the conditions given are true, the result is true. (Only 1 is required)

console.log( true || true );   // true
console.log( false || true );  // true
console.log( true || false );  // true
console.log( false || false ); // false
Copy the code

📖 expand

Q: 1 | | 0 value is what?

👇

👇

👇

👇

The first reaction is true🤣

In JS, | | or operator to do the following things: 🍇 : from left to right operand. 🍈 : Each operand is converted to a Boolean value as it is processed. If the result is true, the calculation is stopped and the initial value of the operand is returned. 🍉 : Returns the last operand if all operands have been evaluated (that is, the conversion result is false).

That is, the value returned is actually the original operand, without Boolean conversions.

📒 conclusion: | | (or) operation of the return value is the first to true value, or all of the false values of the last one

So the answer to the above question is:



🎨 More examples:

console.log( null || 1 ); / / 1 (1 is the first true value) the console. The log (null | | 0 | | 1); / / 1 (the first true value) the console. The log (undefined | | null | | 0); // 0 (all false, return last value)Copy the code




This rule leads to some interesting uses compared to “pure, traditional or operations that deal only with Booleans.”

1. Get the first truth value in a variable list or expression.

🎨 example: Select the one of several variables that has a value. If none has a value, print the default value

// Let firstName = ""; // Let firstName = ""; let lastName = ""; let nickName = "Axjy"; console.log( firstName || lastName || nickName || "Anonymous"); // AxjyCopy the code

2. Short-circuit evaluation

Short-circuit evaluation (also known as minimum evaluation) is an evaluation strategy of logical operators. The second operand is evaluated only if the value of the first operand cannot determine the result of the logical operation. 👉 Wikipedia

Such as | | (or) operation, when the first operand is true, the results must be true, in this case, you don’t need to know the specific value of the second operand.

You can use this effect to make commands that will only be executed if the left side is added false

True | | the console. The log (" not implemented "); False | | the console. The log (" will be performed ");Copy the code

As you can see, the operand of an or operation can be not only a value, but also a variable assignment or function call

&& (and) + expand

The and operation returns true if both operands are true, false otherwise

console.log( true && true );   // true
console.log( false && true );  // false
console.log( true && false );  // false
console.log( false && false ); // false
Copy the code

📖 expand

The && (and) operation can be used to find the first false value

🎨 such as:

// If the first operand is false, // and returns it directly. The second operand is ignored console.log(null && 5); // null console.log( 0 && "no matter what" ); // 0 // If the first operand is true, // the and operation returns the second operand: console.log(1&&0); // 0 console.log( 1 && 5 ); / / 5Copy the code

The and operation does the following: 🍊 : evaluates the operands from left to right. 🍋 : Converts each operand to a Boolean value as it is processed. If the result is false, the calculation is stopped and the initial value of the operand is returned. 🍌 : Returns the last operand if all operands have been evaluated (for example, true values).

📒 Summary: the && (and) operation returns the first false value, or the last of all true values

2, and | | or operation, && (and) operation also can be used as a short circuit, when && (with) the value of the first operand is false, the result must be false.




! (a)

Exclamation sign! Represents a Boolean non operator that takes the opposite value

result = ! value;Copy the code

Priority problem

With operation & priority than or operation | |

A & b | | c & d is equal to (a & b) | | (c & d)Copy the code

Non-operator! Has the highest priority in all logical operators, so it is always in && and | | before execution.

📒 Summary:! (a) > && (and) > | | (or)




Null-value merge operator ‘?? ‘

📖 function: it is mainly used to get a defined value. What is defined? The value is neither null nor undefined.

a ?? The result of b is: – the result is A if A is defined, and – the result is B if a is not defined.

📒 summary: If the first argument is not null/undefined, then?? Returns the first argument. Otherwise, return the second argument.

📖 Application scenario: Common?? Is used to provide a default value for a variable that may be undefined.

🎨 Example: If user is undefined, Anonymous is displayed:

let user;
console.log(user ?? "Anonymous"); // Anonymous
Copy the code

If there is serious, isn’t found, in fact, the above said | | (or) is the same as the operation can be realized, why add null merge operator?? ?

The important differences are:

  • ||Return the firsttrueValue.
  • ??Return the firstThe definedValue.

| | can’t distinguish between false, 0, an empty string “” and null/undefined. They’re all the same — false values. If any one is | | the first parameter, then we will get the second parameter as a result.

In practice, however, we might just want to use the default if the value of the variable is NULL /undefined. That is, when the value is truly unknown or not set.

🎨 example:

let height = 0; console.log(height || 100); // check if height is false, if so, return the second argument 100 console.log(height?? 100); // check whether height is null/undefined, if not, return its value 0Copy the code

Obviously, when 0 is valid, it should not be replaced with the default value, so?? Is the correct result.

?? Is a matter of priority

?? Operators are fairly low-priority, so if you want them to work, you’d better put parentheses around them;

?? And && and | | when used together, if not add parentheses will direct error;






Conditional operator?

In JavaScript, there are two ways to perform different operations based on different conditions

  • Use if statements
  • Use conditional operators?(also known as the “question mark” operator)

Sometimes we need to assign a variable based on a condition. Using the “question mark” operator allows us to do this much more quickly

📖 syntax: let result = condition? value1 : value2;

(Evaluates the conditional result, returning value1 if true, value2 otherwise.)

The operator passes the question mark? Said. It is sometimes called the ternary operator, called “ternary” because there are three operands in the operator.

🎨 example:

console.log( '0' ? 'true' : 'false') // true console.log(0? 'true' : 'false') // falseCopy the code

Multiple ‘? ‘

Using a series of question marks? Operators can return a value that depends on more than one condition.

let score = 100; let message = (score < 60) ? 'Fail! ' : (score < 79) ? 'qualified! ' : (score < 89) ? 'good! ':' Excellent! '; console.log( message );Copy the code

Is equivalent to

If (score < 60) {message = 'score! '; } else if (score < 79) {message = 'pass! '; } else if (score < 89) {message = 'good! '; } else {message = 'Excellent! '; }Copy the code

When are ternary operators appropriate?

Although ternary operators are shorter, they are less readable, so overuse is not recommended;

  • If you need to return one or another value based on a condition, you can use a ternary operator
  • If need be according to the conditionperformDifferent code branches, please useif.


conclusion

Articles will be updated, optimized, and refactored constantly!

References:

Basic operators, maths

Conditional branching: if, ‘? ‘

Logical operators

Nullish coalescing operator ‘?? ‘



🎨 [thumbs up] [concerns] don’t get lost, more front-end dry goods waiting for you to unlock

Phase to recommend

👉 What’s new with the latest version of chrome developer tools?

👉 layui image collection + how to copy the whole website down

👉 Learn JavaScript from 0

Memo | 👉 HTTP status code is commonly used & request & response header & Cookies and collection request method