Hello! In our last lesson, we dug deep into how JavaScript compares values, establishing the golden rule of always using strict equality (===) to avoid the unpredictable behavior of type coercion. You now know how to ask a single question and get a true or false answer.
Today, we'll build on that by learning how to ask multiple questions at once. This lesson introduces logical operators, which are the tools you'll use to combine multiple conditions into more complex and powerful decision-making logic. We'll cover the three core logical operators: && (AND), || (OR), and ! (NOT).
A major focus will be on a concept called short-circuiting. This is a key "under-the-hood" behavior of the && and || operators that not only makes your code more efficient but also unlocks some clever and common programming patterns. Understanding this is essential for writing professional JavaScript.
A Quick Refresher: Truthy and Falsy Values
Before we dive in, let's quickly recall the concept of "truthy" and "falsy" values, as it's fundamental to how logical operators work. In JavaScript, when a non-boolean value is used in a boolean context (like an if statement or with a logical operator), it's coerced into true or false.
Only a few specific values are falsy:
false0(the number zero)""(an empty string)nullundefinedNaN(Not a Number)
Every other value in JavaScript is truthy, including all objects {}, all arrays [], non-empty strings like "hello", and non-zero numbers like -1 or 42.
The Logical Operators
There are three main logical operators that you will use constantly in your programming journey. Let's start with a comprehensive text that covers all three.
The article 'Logical operators' on javascript.info is an excellent reference for this topic. We will use it as our guide.
Just read the brief introduction to familiarize yourself with the four operators. We'll be focusing on the first three: OR (||), AND (&&), and NOT (!).
1. The ! (NOT) Operator
The ! operator is the simplest. It takes a single value, converts it to its boolean equivalent (true or false), and then inverts it.
!truebecomesfalse.!falsebecomestrue.
When used on non-boolean values, it first coerces them.
console.log( !"hello" ); // "hello" is truthy -> !true -> false
console.log( !0 ); // 0 is falsy -> !false -> true
console.log( ![] ); // An empty array is an object, which is truthy -> !true -> false
A common pattern you might see is the double NOT (!!). This is a quick way to explicitly convert any value to its pure boolean equivalent. The first ! inverts it, and the second ! inverts it back.
let name = "Alex";
console.log( !!name ); // !'Alex' -> !true -> false. Then !false -> true.
let score = 0;
console.log( !!score ); // !0 -> !false -> true. Then !true -> false.
2. The || (OR) Operator
The || operator is used to check if at least one of its conditions is true. In its simplest form, with booleans:
true || false; // -> true
false || true; // -> true
true || true; // -> true
false || false; // -> false
However, its behavior is more powerful than this. The || operator doesn't just return true or false. It returns the first truthy value it finds, or the last value if all are falsy.
Let's see this in action.
Let's return to the 'Logical operators' article to understand the full behavior of OR.
Read the sections titled '|| (OR)' and 'OR "||" finds the first truthy value'. Pay close attention to the examples where it returns a non-boolean value like a number or a string. This is the foundation of short-circuiting.
As the article explains, the evaluation happens from left to right.
null || 1->1(becausenullis falsy, so it continues;1is truthy, so it stops and returns1)."" || "Default User" || "Another User"->"Default User"(because""is falsy, but"Default User"is the first truthy value it finds).undefined || 0 || null->null(because all are falsy, so it returns the very last value).
3. The && (AND) Operator
The && operator checks if all of its conditions are true.
true && true; // -> true
true && false; // -> false
false && true; // -> false
false && false; // -> false
Similar to ||, the && operator has a more advanced behavior. It returns the first falsy value it finds, or the last value if all are truthy.
Now, let's look at the corresponding sections for the AND operator in the same article.
Read the sections '&& (AND)' and 'AND "&&" finds the first falsy value'. Notice how its logic is the inverse of the OR operator.
The evaluation is again left to right.
1 && 0->0(because1is truthy, so it continues;0is the first falsy value, so it stops and returns0)."User" && null && 100->null(because"User"is truthy, butnullis the first falsy value it finds).42 && "hello" && true->true(because all values are truthy, so it returns the very last one).
Test your understanding!
What will be the result of the following expressions? Try to work them out before checking the answer.
'cat' && false && 'dog'undefined || null || 3 || 4! (5 && 0) || (5 > 4)
Show answer
false. The&&operator looks for the first falsy value.'cat'is truthy, so it continues.falseis the first falsy value, so the expression short-circuits and returnsfalse.3. The||operator looks for the first truthy value.undefinedis falsy,nullis falsy.3is the first truthy value, so the expression short-circuits and returns3.true. Let's break it down by operator precedence:- Parentheses first:
(5 && 0)evaluates to0(the first falsy value). - The expression becomes
!0 || (5 > 4). !0evaluates totrue.(5 > 4)evaluates totrue.- The expression is now
true || true, which istrue. Because of short-circuiting, the(5 > 4)part wouldn't even be evaluated, as the!0part is alreadytrue.
- Parentheses first:
Deep Dive: Short-Circuit Evaluation
We've used the term "short-circuit" a few times. This is the "under the hood" mechanism you've been waiting for. It means that the JavaScript engine stops evaluating a logical expression as soon as the final result is determined.
- For
&&, if it finds a falsy value, it knows the whole expression must befalse, so it stops and returns that falsy value. - For
||, if it finds a truthy value, it knows the whole expression must betrue, so it stops and returns that truthy value.
This isn't just a performance trick; it's a feature that enables powerful patterns. The following video provides a fantastic visual demonstration of this process.
SHORT-CIRCUIT EVALUATION in JavaScript, Simplified
The video 'SHORT-CIRCUIT EVALUATION in JavaScript, Simplified' by Deeecode visualizes exactly when JavaScript stops evaluating an expression. This is a perfect illustration of the concept.
Watch from the beginning to 06:12. Pay close attention to the console logs. Notice how some console.log statements are never executed because the expression short-circuits before reaching them. This is the key takeaway.
Practical Uses of Short-Circuiting
As you saw in the video, this behavior is extremely useful. Here are the two most common patterns.
1. Using || to Set Default Values
Imagine you have a variable that might be undefined or an empty string, and if it is, you want to use a default value.
let username = ""; // This could come from a user input form
// Before, you might write an if statement:
// let displayName;
// if (username) {
// displayName = username;
// } else {
// displayName = "Guest";
// }
// With short-circuiting, it's one line:
let displayName = username || "Guest";
console.log(`Welcome, ${displayName}!`); // Welcome, Guest!
How it works:
usernameis"", which is falsy.- The
||operator cannot determine the result yet, so it continues to the next operand. - The next operand is
"Guest", which is truthy. - The operator short-circuits and returns
"Guest". ThedisplayNamevariable is assigned this value.
If username was "Alice", the expression "Alice" || "Guest" would immediately return "Alice" because it's the first truthy value.
2. Using && for Conditional Execution
Sometimes you only want to run a function or an expression if a certain condition is true.
let userIsAdmin = true;
let userCanDelete = false;
function deletePost() {
console.log("Post deleted!");
}
// Instead of:
// if (userIsAdmin) {
// deletePost();
// }
// You can use &&:
userIsAdmin && deletePost(); // 'deletePost' is called, "Post deleted!" is logged.
// And for the other user:
userCanDelete && deletePost(); // 'userCanDelete' is false, so the expression short-circuits.
// The deletePost() function is NEVER called.
How it works:
userIsAdministrue. The&&operator cannot determine the result yet, so it continues. It evaluates the right side, which callsdeletePost().userCanDeleteisfalse. The&&operator finds a falsy value and immediately short-circuits, returningfalse. ThedeletePost()function on the right is never reached.
While this pattern is common, the javascript.info article correctly notes that a simple if statement is often more readable and explicit. Use your judgment!
Conclusion
Mastering logical operators and their short-circuiting behavior is a huge step forward. You've moved from simple comparisons to creating compound logic that is at the heart of every application.
Key Takeaways:
- Logical Operators:
!inverts a boolean,&&requires all operands to be truthy, and||requires at least one to be truthy. - Truthy/Falsy: These operators coerce non-boolean values, making it crucial to know the 6 falsy values (
false,0,"",null,undefined,NaN). - Return Values:
&&and||don't always return a boolean. They return the actual value that stopped the evaluation.||returns the first truthy value (or the last value if all are falsy).&&returns the first falsy value (or the last value if all are truthy).
- Short-Circuiting: This is the core mechanism where evaluation stops as soon as the outcome is known. It's used for performance and enables common patterns like setting default values (
||) and conditional execution (&&).
Next Up:
We'll conclude our module on operators by looking at some convenient shortcuts: shorthand assignment operators like += and *= and the increment/decrement operators ++ and --. These will help you write more concise and efficient code.