Зміст:
Logical AND (&&)
The logical AND ( && ) (logical conjunction) operator for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .
More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.
Try it
Syntax
Description
If a value can be converted to true , the value is so-called truthy. If a value can be converted to false , the value is so-called falsy.
Examples of expressions that can be converted to false are:
- false ;
- null ;
- NaN ;
- 0 ;
- empty string ( “” or ” or “ );
- undefined .
The AND operator preserves non-Boolean values and returns them as they are:
= "" && "foo"; // result is assigned "" (empty string) result = 2 && 0; // result is assigned 0 result = "foo" && 4; // result is assigned 4
Even though the && operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.
Short-circuit evaluation
The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false , the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.
Consider the pseudocode below.
(some falsy expression) && expr
The expr part is never evaluated because the first operand (some falsy expression) is evaluated as falsy. If expr is a function, the function is never called. See the example below:
function A() console.log("called A"); return false; > function B() console.log("called B"); return true; > console.log(A() && B()); // Logs "called A" to the console due to the call for function A, // && evaluates to false (function A returns false), then false is logged to the console; // the AND operator short-circuits here and ignores function B
Operator precedence
The AND operator has a higher precedence than the OR operator, meaning the && operator is executed before the || operator (see operator precedence).
true || false && false; // true true && (false || false); // false (2 === 3) || (4 0) && (1 === 1); // false
Examples
Using AND
The following code shows examples of the && (logical AND) operator.
= true && true; // t && t returns true a2 = true && false; // t && f returns false a3 = false && true; // f && t returns false a4 = false && 3 === 4; // f && f returns false a5 = "Cat" && "Dog"; // t && t returns "Dog" a6 = false && "Cat"; // f && t returns false a7 = "Cat" && false; // t && f returns false a8 = "" && false; // f && f returns "" a9 = false && ""; // f && f returns false
Conversion rules for booleans
Converting AND to OR
The following operation involving booleans:
Converting OR to AND
The following operation involving booleans:
Removing nested parentheses
As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.
The following composite operation involving booleans:
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Sep 25, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2024 by individual mozilla.org contributors. Content available under a Creative Commons license.
Java Підручник
Java – це популярна мова програмування. Java використовується для розробки мобільних додатків, вебдодатків, настільних програм, ігор та багато іншого. Найвідоміші операційні системи, які були написані мовою програмування Java: Android OS, BlackBerry Tablet OS та JavaOS. Почати вивчення Java негайно! »
Приклади в кожній главі
Наш редактор “Спробуйте самі” спрощує вивчення Java. Ви можете редагувати Java-код і відразу переглядати результат в своєму браузері.
Приклад
Ми рекомендуємо вивчати теми цього підручника в послідовності, зазначеної в лівому меню (або відкривши меню бургер, якщо ви користуєтеся мобільними гаджетами). Java – об’єктно-орієнтована мова, і деякі концепції можуть бути новими. Робіть перерви, коли це необхідно, і переглядайте приклади стільки разів, скільки необхідно.
Java Вправи
Вчіться на прикладах
Вчіться на прикладах! Цей підручник доповнює всі пояснення пояснюючими прикладами. Переглянути всі Java приклади
Java Вікторина
Java Довідник
Скачати Java
Здайте Java іспит – Отримайте свій Сертифікат!
Онлайн Сертифікація W3Schools
Ідеальне рішення для професіоналів, яким необхідно збалансувати роботу, сім’ю та кар’єру. Більше 25 000 сертифікатів уже видано!
Також ви можете ознайомитись із підручником по Java із сайту hyperskill.org в перекладі українською мовою.
До відома.
- Eclipse – інтегроване середовище розробки програмного забезпечення
- Android Studio – середовище розробки для мобільної платформи Android
- Minecraft – популярна відеогра, яка використовує Java для своєї реалізації
- Apache Cassandra – система керування базами даних з відкритим кодом
- Apache Lucene – бібліотека повнотекстового пошуку та індексування даних
- Spring Framework – фреймворк для розробки веб-додатків на Java
- Hibernate – бібліотека для роботи з базами даних на основі Java Persistence API
- Jenkins – інструмент для автоматизації процесу збирання та тестування програмного забезпечення
Це лише кілька з безлічі програм та вебдодатків, які були створені з використанням мови програмування Java.