You get a bonus - 1 coin for daily activity. Now you have 1 coin

Logical operators

Lecture




  1. || (OR)
  2. Short cycle of calculations
  3. OR value
  4. && (AND)
  5. ! (NOT)

JavaScript is supported in operators || (Or), && (and) and ! (NOT).

They are called “logical” , but in JavaScript they can be applied to values ​​of any type and also return values ​​of any type.

|| (OR)

The OR operator looks like a double vertical bar symbol:

result = a || b;

Logical OR in classical programming works as follows: “if at least one of the arguments is true , then it returns true , otherwise, false ”.

It turns out the following table of results:

1 alert( true || true ); // true
2 alert( false || true ); // true
3 alert( true || false ); // true
4 alert( false || false ); // false

When calculating OR in JavaScript, you can use any values. In this case, they will be interpreted as logical.

For example, the number 1 will be taken as true , and 0 as false :

1 if ( 1 || 0 ) { // сработает как if( true || false )
2    alert( 'верно' );
3 }

Usually the OR operator is used in if to check if at least one of the conditions is met, for example:

1 var hour = 9;
2
3 if (hour < 10 || hour > 18) {
4    alert( 'Офис до 10 или после 18 закрыт' );
5 }

More conditions can be passed:

1 var hour = 12, isWeekend = true ;
2
3 if (hour < 10 || hour > 18 || isWeekend) {
4    alert( 'Офис до 10 или после 18 или в выходной закрыт' );
5 }

Short cycle of calculations

JavaScript calculates several OR from left to right. At the same time, in order to save resources, the so-called “short calculation cycle” is used .

Suppose several OR are calculated in a row: a || b || c || ... a || b || c || ... a || b || c || ... If the first argument is true , then the result will certainly be true (at least one of the values ​​is true ), and the other values ​​are ignored.

This is especially noticeable when the expression passed as the second argument has a third-party effect — for example, assigns a variable.

When you run the example below, assignment x will not occur:

1 var x;
2
3 true || (x = 1); // просто вычислим ИЛИ, без if
4
5 alert(x); // undefined, x не присвоен

... And in the example below, the first argument is false , so OR will try to calculate the second, thereby triggering the assignment:

1 var x;
2
3 false || (x = 1);
4 alert(x); // 1

OR value

So, as we can see, the OR operator calculates exactly as many values ​​as necessary - before the first true .

The OR operator returns the value at which the calculation stopped.

Examples:

1 alert( 1 || 0 ); // 1
2 alert( true || 'неважно что' ); // true
3
4 alert( null || 1 ); // 1
5 alert( undefined || 0 ); // 0

It is used, in particular, to select the first “true” value from the list:

1 var undef; // переменная не присвоена, т.е. равна undefined
2 var zero = 0;
3 var emptyStr = "" ;
4 var msg = "Привет!" ;
5
6 var result = undef || zero || emptyStr || msg || 0; result = undef || zero || emptyStr || msg || 0;
7
8 alert(result) // выведет "Привет!" - первое значение, которое является true // выведет "Привет!" - первое значение, которое является true

Importance: 3

What will the code below?

alert( alert(1) || 2 || alert(3) );

Decision

Answer: first 1 , then 2 .

1 alert( alert(1) || 2 || alert(3) );

The call to alert does not return a value, or, in other words, returns undefined .

  1. First operator OR || will execute the first alert(1) , get undefined and go on to the second operand.
  2. Since the second operand 2 is true, the calculation will end with the result undefined || 2 undefined || 2 will be 2 , which will be displayed by an external alert( .... ) .

The second operator || will not be executed, execution to alert(3) will not reach, therefore 3 will not be displayed.

[Open task in new window]

&& (AND)

The AND operator is written as two ampersands && :

result = a && b;

In classical programming, and returns true if both arguments are true, otherwise false

1 alert( true && true ); // true
2 alert( false && true ); // false
3 alert( true && false ); // false
4 alert( false && false ); // false

Example:

1 var hour = 12, minute = 30;
2
3 if (hour == 12 && minute == 30) {
4    alert( 'Время 12:30' );
5 }

As in OR, any values ​​are allowed:

1 if ( 1 && 0 ) { // вычислится как true && false
2    alert( 'не сработает, т.к. условие ложно' );
3 }

The same principle of “short cycle of calculations” applies to And, but a bit differently than to OR.

If the left argument is false , the AND operator returns it and ends the calculation. Otherwise, it calculates and returns the right argument.

For example:

1 // Первый аргумент - true,
2 // Поэтому возвращается второй аргумент
3 alert(1 && 0); // 0
4 alert(1 && 5); // 5
5
6 // Первый аргумент - false,
7 // Он и возвращается, а второй аргумент игнорируется
8 alert( null && 5); // null
9 alert(0 && "не важно" ); // 0

Importance: 3

What will the code below?

alert( alert(1) && alert(2) );

Decision

Answer: 1 , undefined .

1 alert( alert(1) && alert(2) );

The call to alert does not return a value, or, in other words, returns undefined .

Therefore, it won't get to the right alert , the calculations will end on the left.

[Open task in new window]

The priority of the operator AND && greater than OR || i.e. it is executed before.

Therefore, in the following code, the right AND will be calculated first: 1 && 0 = 0 , and only then - OR.

1 alert(5 || 1 && 0); // 5

Do not use && instead of if

The && operator in simple cases can be used instead of if , for example:

1 var x = 1;
2
3 (x > 0) && alert( 'Больше' );

The action on the right side of && will be executed only if calculations reach it. That is, if the left side is true .

It turned out analog:

1 var x = 1;
2
3 if (x > 0) {
4    alert( 'Больше' );
5 }

However, as a rule, if better read and understood. It is more obvious, therefore it is better to use it. This, however, also applies to other non-obvious uses of language features.

! (NOT)

The operator is NOT the easiest. He gets one argument. Syntax:

var result = !value;

Actions ! :

  1. First, the argument is boolean true/false .
  2. Then returns the opposite value.

For example:

1 alert( ! true ) // false
2 alert( !0 ) // true

In particular, doubles are NOT used to convert values ​​to a logical type:

1 alert( !! "строка" ) // true
2 alert( !! null ) // false

Importance: 3

Write an if condition to verify that age is between 14 and 90 inclusive.

"Inclusive" means that the ends of the gap are included, that is, age can be equal to 14 or 90 .

Decision

if (age >= 14 && age <= 90)

[Open task in new window]

Importance: 3

Write an if condition to check for the fact that age NOT between 14 and 90 inclusive.

Make two variants of the condition: the first using the NOT operator ! , the second - without this operator.

Decision

First option:

if ( !(age >= 14 && age <= 90) )

The second option:

if (age < 14 || age > 90)

[Open task in new window]

Importance: 5

Which of these if are valid, i.e. will be executed? What values ​​will be the results of expressions in if conditions?

if (-1 || 0) alert( 'первое' );
if (-1 && 0) alert( 'второе' );
if ( null || -1 && 1) alert( 'третье' );

Solution example:

// 1. Да, выполнится
// 2. Выражение внутри false || 1 будет равно 1
if ( false || 1) alert( 'тест' );

Decision

Answer: the first and third will be executed. Details:

01 // Да, выполнится, т.к. -1 в логическом контексте true
02 // -1 || 0 = -1
03 if (-1 || 0) alert( 'первое' );
04
05 // Не выполнится, т.к. -1 интерпретируется как true, а 0 как false
06 // -1 && 0 = 0
07 if (-1 && 0) alert( 'второе' );
08
09 // Да, выполнится
10 // оператор && имеет больший приоритет, чем ||
11 // так что -1 && 1 выполнится раньше, будет null || 1 = 1
12 // получится null || -1 && 1 -> null || 1 -> 1
13 if ( null || -1 && 1) alert( 'третье' );
created: 2014-10-07
updated: 2024-11-14
346



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone