Logical operator

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

Although they are called “logical” operators, these operators can be applied to any type of value, not just Boolean values. Their results can also be of any type.

Let’s take a closer look.

| | (or)

The two vertical symbols represent the or operation:

result = a || b;
Copy the code

In traditional programming, logic may only be able to manipulate Boolean values. Returns true if any of the arguments in the operation are true, false otherwise.

In JavaScript, logical operators are more flexible and powerful. But first let’s look at what happens when the operands are Booleans.

Here are four possible logical combinations:

alert( true || true );   // true
alert( false || true );  // true
alert( true || false );  // true
alert( false || false ); // false
Copy the code

As we can see, the result is true except in the case where both operands are false.

If the operand is not a Boolean, it will be converted to a Boolean to participate in the operation.

For example, the number 1 would be true and the number 0 would be false:

if (1 || 0) { / / working principle of the if (true | | false)
  alert( 'truthy! ' );
}
Copy the code

In most cases, logic or | | will be used in the if statement, used to test whether there is any given condition is true.

Such as:

let hour = 9;

if (hour < 10 || hour > 18) {
  alert( 'The office is closed.' );
}
Copy the code

We can pass in more conditions:

let hour = 12;
let isWeekend = true;

if (hour < 10 || hour > 18 || isWeekend) {
  alert( 'The office is closed.' ); / / is weekend
}
Copy the code

Or to find the first truth value

The logic mentioned above is somewhat traditional. Let’s take a look at JavaScript’s “add-on” features.

The extended algorithm is shown below.

Given the value of more than one participating or operation:

result = value1 || value2 || value3;
Copy the code

Or the operator | | do the following things:

  • Evaluate the operands from left to right.
  • Each operand is converted to a Boolean value as it is processed. If the result istrue, stops calculation and returns the initial value of the operand.
  • If all of the operands are evaluated (i.e., the conversion results arefalse), returns the last operand.

The value returned is the original form of the operand and no Boolean conversion is performed.

That is, a or “| |” chain operations, will return to the first true value, if there is no true value, it returns the last value of the chain.

Such as:

alert( 1 || 0 ); // 1 (true)
alert( true || 'no matter what' ); // (true is true)

alert( null || 1 ); // 1 (1 is the first truth value)
alert( null || 0 || 1 ); // 1 (first true value)
alert( undefined || null || 0 ); // 0 (all conversions are false and return the last value)
Copy the code

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

  1. Gets the first truth value of a list of variables or expression.

    Suppose we have several variables, which may contain some data or be null/undefined. We need to pick the first variable that contains the data.

    We can use or operation | | :

    let currentUser = null;
    let defaultUser = "John";
    
    let name = currentUser || defaultUser || "unnamed";
    
    alert( name ); // Select "John" -- the first truth value
    Copy the code

    If currentUser and defaultUser are both false, the result is “occurrences”.

  2. Short-circuit value.

    Operands can be arbitrary expressions, not just values. The or operation evaluates and tests each operand from left to right. When the first truth value is found, the calculation stops and the value is returned. This process is called “short-circuiting” because it minimizes the number of left-to-right calculations.

    When the expression is used as a second argument and has certain side effects, such as variable assignment, the short-circuit value is clearly visible.

    If we run the following example, x will not be assigned:

    let x;
    
    true || (x = 1);
    
    alert(x); // undefined because (x = 1) is not executed
    Copy the code

    If the first argument is false, or the operation continues and the second argument is evaluated, the assignment operation is run.

    let x;
    
    false || (x = 1);
    
    alert(x); / / 1
    Copy the code

    Assignment is just a very simple case. There may be side effects, if the calculation does not arrive, the side effects will not occur.

    As we have seen, this usage is “short form of if statement”. The first operand is converted to a Boolean, and if false, the second argument is executed.

    In most cases, it’s better to use a regular if statement, which makes the code more readable, but sometimes it can be concise.

&& (with)

The two ampersands represent the && and operations:

result = a && b;
Copy the code

In traditional programming, the and operation returns true if both operands are true, and false otherwise:

alert( true && true );   // true
alert( false && true );  // false
alert( true && false );  // false
alert( false && false ); // false
Copy the code

Examples of using the if statement:

let hour = 12;
let minute = 30;

if (hour == 12 && minute == 30) {
  alert( 'Time is 12:30' );
}
Copy the code

As with or, the operands of and can be of any type:

if (1 && 0) { // execute as true && false
  alert( "won't work, because the result is falsy" );
}
Copy the code

Look for the first false value with the operation

Give values for more than one participation and operation:

result = value1 && value2 && value3;
Copy the code

The && operation does the following:

  • Evaluate the operands from left to right.
  • Each operand is converted to a Boolean value as it is processed. If the result isfalseStops the calculation and returns the initial value of the operand.
  • If all of the operands are evaluated (i.e., the conversion results aretrue), returns the last operand.

In other words, the and operator returns the first false value, and the last if there is no false value.

The above rule is very similar to the or operation. The difference is that an operation returns the first false value whereas an or operation returns the first true value.

Such as:

// If the first operator is true,
// Return the second operand:
alert( 1 && 0 ); / / 0
alert( 1 && 5 ); / / 5

// If the first operator is false,
// Return it directly with the operation. The second operand is ignored
alert( null && 5 ); // null
alert( 0 && "no matter what" ); / / 0
Copy the code

We can also concatenate multiple values on a single line of code. See if the first false value is returned:

alert( 1 && 2 && null && 3 ); // null
Copy the code

If all values are true, the last value will be returned:

alert( 1 && 2 && 3 ); // 3, the last value
Copy the code

With the operation&&The or operator||Before performing

With operation & priority than or operation | |.

So the code a & b | | c & d completely like && expression with parentheses: (a & b) | | (c & d).

Like or, ampersand can sometimes replace if.

Such as:

let x = 1;

(x > 0) && alert( 'Greater than zero! ' );
Copy the code

The code to the right of && cannot be executed until the operation reaches there. That is, if and only if (x > 0) returns a true value.

So we can basically get the following:

let x = 1;

if (x > 0) {
  alert( 'Greater than zero! ' );
}
Copy the code

Code variants with && look shorter. But if is more obvious and readable.

So the recommendation is to choose the structure of the code according to the purpose. If is needed, && is needed.

! (a)

Exclamation sign! Represents a Boolean non operation.

The syntax is fairly simple:

result = ! value;Copy the code

The operator takes an argument and operates as follows:

  1. To convert operands to Boolean types:true/false.
  2. Return the opposite value.

Such as:

alert( !true ); // false
alert( !0 ); // true
Copy the code

Two non-operations!! Sometimes used to convert a value to a Boolean type:

alert( !!"non-empty string" ); // true
alert( !!null ); // false
Copy the code

That is, the first nonoperation converts the value to a Boolean type and negates it, and the second nonoperation negates it again. Finally, we have a transformation from an arbitrary value to a Boolean value.

There are more detailed ways to do the same — a built-in Boolean function:

alert( Boolean("non-empty string"));// true
alert( Boolean(null));// false
Copy the code

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

Homework assignments

Do the questions yourself and then look at the answers.

What is the result of the or operation?

Importance: ⭐️⭐ ⭐️⭐️

What will the following output be?

alert( null || 2 || undefined );
Copy the code

2. What is the result of the OR operation and alerts?

Importance: ⭐️⭐️ ️

What does the following code output?

alert( alert(1) | |2 || alert(3));Copy the code

3. What are the results of the operation?

Importance: ⭐️⭐ ⭐️⭐️

What will the following code show?

alert( 1 && null && 2 );
Copy the code

4. What is the result of the alerts connected to the operation?

Importance: ⭐️⭐️ ️

What will this code show?

alert( alert(1) && alert(2));Copy the code

5. The result of or an operation, an operation, or a series of operations

Importance: ⭐️⭐ ⭐️⭐️

What will be the result?

alert( null || 2 && 3 || 4 );
Copy the code

6. Check whether the value is within the range

Importance: ⭐️⭐️ ️

Write an “if” conditional to check if age is between 14 and 90 closed.

“Closed interval” means that the value of age can be either 14 or 90.

7. Check whether the detected value is outside the range

Importance: ⭐️⭐️ ️

Write an if conditional to check that age is not in the closed range 14 to 90.

Create two expressions: the first uses a non-operation! No need for the second one.

8. A question about “if”

Importance: ⭐️⭐ ⭐️⭐️

Which of the following alerts will be executed?

if(…) What is the result of the expression inside the statement?

if (- 1 || 0) alert( 'first' );
if (- 1 && 0) alert( 'second' );
if (null || - 1 && 1) alert( 'third' );
Copy the code

9. Login verification

Importance: ⭐️⭐️ ️

Implement code for login verification using Prompt.

If the visitor enters “Admin, “use prompt to get the password if the user name is empty or key:Esc is pressed — showing “Canceled” or “I don’t know you” if it’s another string.

The password verification rules are as follows:

  • If “TheMaster” is entered, “Welcome!” is displayed. .
  • Other strings — display “Wrong Password “,
  • Empty string or Canceled input, showing “Canceled.”

Flow chart:

Use nested if blocks. Pay attention to the overall readability of the code.

Tip: Enter an empty string and prompt will get an empty string ”. During Prompt, pressing key:ESC returns null.

The answer:

Reply 1-2-11 in the background of wechat public account “Technology Chat” to obtain the answer to this question.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Scan the QR code below and follow the wechat public account “Technology Chat” to subscribe for more exciting content.