- Логические операторы в JavaScript
- Логическое И &&
- Пример №1
- Пример №2
- Пример №3
- Пример №4
- Пример №5
- Логическое ИЛИ ||
- Пример №6
- Пример №7
- Пример №8
- Пример №9
- Пример №10
- Логическое НЕ !
- Итого
- Javascript if with and operator
- # Specify multiple conditions in an if statement
- # Using the logical AND (&&) operator - all conditions have to be met
- # Using the logical AND (&&) and logical OR (||) operators in a single if
- # Using the every() method to specify multiple conditions
- # Using the some() method to specify multiple conditions
- # Using an if/else if /else statement
- # Additional Resources
Логические операторы в JavaScript
В языке программирования JavaScript есть пять логических операторов || (или), && (и), ! (не), менее известный ?? оператор нулевого слияния, который еще относят к частному случаю оператора || (или) и тернарный оператор. Логические операторы используются для комбинирования булевых значений — true (истина) и false (ложь) и часто применяются в сочетании с операторами отношений (>, >=, true либо false .
Если значение равно 0, -0, null, false, NaN, undefined или «» (пустая строка) — результат false . Все остальное, включая строку «false» — результат true .
Остановимся подробнее на операторах || (или), && (и) и ! (не)
Логическое И &&
&& (двой знак амперсанда) — это бинарный оператор, который представляет собой логически «и» и принимает значение true только в том случае, когда оба операнда истинны, в противном случае false .
Рассмотри результат при каждой возможной логической комбинации.
console.log( true && true ); // true console.log( false && true ); // false console.log( true && false ); // false console.log( false && false ); // false
Пример №1
let examScores1 = parseInt(prompt("Введите баллы за первый экзамен")); let examScores2 = parseInt(prompt("Введите баллы за второй экзамен")); if (examScores1 >= 60 && examScores2 >= 60) < alert('Вы допущены к следующему экзамену'); >else
Пример №2
let examScores1 = parseInt(prompt("Введите баллы за первый экзамен")); let examScores2 = parseInt(prompt("Введите баллы за второй экзамен")); let examScores3 = parseInt(prompt("Введите баллы за третий экзамен")); if (examScores1 >= 60 && examScores2 >= 60 && examScores3 >= 60) alert('Вы поступили в университет'); else alert('Вы не поступили в университет');
При необходимости можно передать и больше условий && (и)
Пример №3
В качестве операнда && допускаются любые другие значения
Пример №4
console.log("текст" && undefined && 40); // значение = undefined console.log("текст" && 30 && 0 && 40); // значение = 0 console.log(40 && 30 && 3 && "текст"); // значение = текст
В случае, когда операторов && несколько:
- вычисление идет слева направо;
- операнды принимают значение true или false ;
- если операнд false сравнение останавливается, а результат — значение этого операнда;
- если все значения true , тогда возвращается последний операнд;
- если возвращаемый операнд не является булевым — результат значение операнда.
Если сказать по другому результат — это значение первого false или последнего операнда.
Пример №5
Приоритет у && (и) выше чем у || (или), таким образом сначала выполнить сравнение в левой и правой части выражения.
Логическое ИЛИ ||
|| (двойная вертикальная черта) — это бинарный оператор, который представляет собой логическое «или» и принимает значение true в том случае, когда все или одно из значений операндов истинно, в противном случае false .
Рассмотри результат при каждой возможной логической комбинации.
console.log( true || true ); // true console.log( false || true ); // true console.log( true || false ); // true console.log( false || false ); // false
Пример №6
let examScores = parseInt(prompt("Сколько баллов вы получили за 3 экзамена")); let runningSpeed = parseInt(prompt("Как быстро вы пробегаете 100 метров")); if (examScores >= 250 || runningSpeed < 12) < alert('Вы поступили в университет'); >else
Пример №7
let examScores = parseInt(prompt("Сколько баллов вы получили за 3 экзамена")); let runningSpeed = parseInt(prompt("Как быстро вы пробегаете 100 метров")); let placeOlympiad = parseInt(prompt("Какое место вы заняли на всероссийской олимпиаде")); if (examScores >= 250 || runningSpeed < 11 || placeOlympiad == 1) < alert('Вы поступили в университет'); >else
При необходимости можно передать и больше условий || (или).
Пример №8
if (1 || 0) < // 1 - true, 0 - false console.log("Результат - true") >else console.log( "Результат - false" );
В качестве операнда || допускаются любые другие значения.
Пример №9
console.log(undefined || "текст" || 40); // значение = текст console.log("" || null || 0 || "текст"); // значение = текст console.log(40 || 30 || 3 || "текст"); // значение = 40
В случае, когда операторов || несколько:
- вычисление идет слева направо;
- операнды принимают значение true или false ;
- если операнд true сравнение останавливается, а результат — значение этого операнда;
- если все значения false , тогда возвращается последний операнд;
- если возвращаемый операнд не является булевым — результат значение операнда.
Если сказать по другому результат — это значение первого true или последнего операнда.
Пример №10
let scores = parseInt(prompt("Сколько баллов вы набрали на экзамене")); scores < 90 || alert('Ваша оценка 5');
В результате «сокращенного вычисления» (когда вычисления заканчиваются, если результат уже известен) с помощью || (или), можно реализовывать и такие конструкции. В данном примере это своеобразная замена if , которая может быть удобна в определенных случаях.
Логическое НЕ !
! (восклицательный знак) - это унарный оператор, который располагается перед операндом и приводит аргумент к логическому true или false , а затем возвращает противоположное значение.
console.log( !true ); // false console.log( !false ); // true console.log( !'текст' ); // false console.log( !5 ); // false console.log( !0 ); // true
В свою очередь двойное отрицание !! используется для приведения значения к логическому типу.
console.log( !!true ); // true console.log( !!false ); // false console.log( !!'текст' ); // true console.log( !!5 ); // true console.log( !!0 ); // false
Эквивалентом такой конструкции служит встроенная функция Boolean
console.log( Boolean('текст') ); // true console.log( Boolean(5) ); // true console.log( Boolean(0) ); // true
Логически оператор ! имеет более высокий приоритет, нежели || и && , поэтому при необходимости сделать отрицание выражения, конструкцию нужно брать в скобки.
console.log( !(true && false) ); // true console.log( !true && false ); // false console.log( !(true || true) ); // false console.log( !true || true ); // true
Итого
В данном уроке мы подробно рассмотрели логические операторы:
- && (и) - возвращает true , когда оба операнда true , в противном случае false ;
- || (или) - возвращает false , если два операнда false , во всех остальных случаях true ;
- ! (не) - возвращает true , если значение операнда false и наоборот;
Из этих трех операторов наивысший приоритет исполнения имеет ! (не), затем && (и) и только потом || (или).
Skypro - научим с нуля
Javascript if with and operator
Last updated: Jan 2, 2023
Reading time · 4 min
# Specify multiple conditions in an if statement
Use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement.
When using logical AND (&&), all conditions have to be met for the if block to run.
When using logical OR (||), at least one condition has to be met for the if block to run.
Copied!// ✅ Using logical OR (||) - at least 1 condition has to be met const num = 5; if (num > 10 || num > 5 || num > 0) // 👇️ if block runs console.log('✅ at least one condition is met'); > else console.log('⛔️ neither condition is met'); >
We used the logical OR (||) operator to chain multiple conditions in an if statement.
If none of the conditions return true , the else block will run.
# Using the logical AND (&&) operator - all conditions have to be met
Here's an example of specifying multiple conditions using the logical AND (&&) operator.
Copied!// ✅ Using logical AND (&&) - all conditions have to be met const num = 5; if (10 > num && 6 > num) // 👇️ if block runs console.log('✅ all conditions are met'); > else console.log('⛔️ not all conditions are met'); >
When using the logical AND (&&) operator in an if statement, all conditions have to be met for the if block to run.
Both conditions in the example return true , so the if block is run.
# Using the logical AND (&&) and logical OR (||) operators in a single if
You can also use the logical AND (&&) and logical OR (||) operators in a single if statement.
Copied!const num = 5; if ((num > 20 && num > 30) || (10 > num && 15 > num)) // 👇️ if block runs console.log('✅ at least one condition is met'); > else console.log('⛔️ neither condition is met'); >
First, the condition to the left (in the parentheses) is evaluated and returns false .
Then the logical OR (||) operator evaluates the condition to the right.
The condition to the right evaluates to true , so the if block is run.
Notice that we used parentheses to group our code and make it more readable.
# Using the every() method to specify multiple conditions
This is a two-step process:
- Add the conditions to an array.
- Use the Array.every() method to iterate over the array.
- Return each condition.
Copied!const num = 5; const conditions = [num > 1, num > 2, num > 3]; const allConditionsMet = conditions.every(condition => condition); console.log(allConditionsMet); // 👉️ true if (allConditionsMet) // 👇️ this runs console.log('All conditions are met'); > else console.log('Not all conditions are met'); >
We stored the conditions we want to check for in an array.
The function we passed to the Array.every method gets called with each element in the array.
On each iteration, we return the current condition as is.
The every() method returns true if the callback function returns a truthy value on all iterations.
The code sample checks if all of the specified conditions are met.
# Using the some() method to specify multiple conditions
If you need to check if at least one of the specified conditions is met, use the Array.some() method.
- Add the conditions to an array.
- Use the Array.some() method to iterate over the array.
- Return each condition.
Copied!const num = 5; const conditions = [num > 10, num > 20, num > 3]; const atLeastOneConditionMet = conditions.some(condition => condition); console.log(atLeastOneConditionMet); // 👉️ true if (atLeastOneConditionMet) // 👇️ this runs console.log('At least one condition is met'); > else console.log('None of the conditions are met'); >
The function we passed to the Array.some() method gets called with each condition from the array.
On each iteration, we return the condition as is.
If the callback function returns a truthy value at least once, the some() method returns true and short-circuits.
Otherwise, the some() method iterates over the entire array and returns false .
The code sample checks if at least one of the specified conditions is met.
# Using an if/else if /else statement
You can also use an if/else if/else statement to specify multiple conditions.
Copied!const num = 5; if (num > 5) console.log('num is greater than 5'); > else if (num > 0) // 👇️ this runs console.log('num is greater than 0'); > else console.log('num is less than or equal to 0'); >
The if statement checks if the variable stores a number greater than 5 .
The condition isn't met, so the else if condition is evaluated.
The condition is met, so the else if block is run.
The else statement is only run if the conditions in the if and else if statements evaluate to false .
Copied!const num = 0; if (num > 5) console.log('num is greater than 5'); > else if (num > 0) console.log('num is greater than 0'); > else // 👇️ this runs console.log('num is less than or equal to 0'); >
The num variable stores a value of 0 , so the if and else if statements evaluate to falsy , so the else block is run.
You can also use as many else if statements as necessary.
Copied!const num = -5; if (num > 5) console.log('num is greater than 5'); > else if (num > 0) console.log('num is greater than 0'); > else if (num > -10) // 👇️ this runs console.log('num is greater than -10'); > else console.log('num is less than or equal to -10'); >
The second else if statement checks if the num variable stores a value greater than -10 .
The condition is met, so its code block runs.
If none of the conditions are met, the else block runs.
You don't have to specify an else statement if you don't need it.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.