Photo by Kenny Leys on Unsplash

JavaScript’s && (logical AND) and || (logical OR) operators offer a powerful optimization technique called short-circuit evaluation. This means they can potentially stop evaluating the entire expression as soon as the outcome is clear based solely on the first operand. This approach can improve performance and code readability in certain scenarios.

Logical AND (&&)

The && operator returns the following values:

true: If both operands evaluate to true.The first falsy operand: If the first operand is false, null, undefined, 0, NaN, or an empty string (“”), the expression short-circuits and returns that first operand without evaluating the second operand.

Example 1: AND for Conditional Execution

function greet(name) {
if (name && name.trim()) { // Short-circuit if name is falsy or empty
console.log(“Hello, ” + name + “!”);
} else {
console.log(“Hello, world!”);
}
}
greet(“”); // Output: Hello, world! (name is empty)
greet(null); // Output: Hello, world! (name is null)
greet(“Alice”); // Output: Hello, Alice!

Here, name && name.trim() leverages short-circuiting. If name is falsy or empty, it short-circuits and returns the falsy value, preventing the unnecessary execution of name.trim(). This ensures a cleaner greeting for users who haven’t provided a name or entered an empty string.

Example 2: AND for Accessing Nested Properties Safely

const user = {
profile: {
name: “Bob”,
},
};

const greeting = user && user.profile && user.profile.name; // Safe access
console.log(greeting); // Output: Bob

// Example of potential error without short-circuiting
console.log(user.profile.name); // Error: Cannot read property ‘name’ of undefined (if user.profile is null)

In this example, the expression user && user.profile && user.profile.name safely accesses the name property only if both user and user.profile exist. This prevents potential errors that might occur if we try to access properties of non-existent objects.

Example 3: AND for Chained Function Calls (Optional Chaining Alternative)

JavaScript

function calculateDiscount(customer) {
if (customer && customer.membership && customer.membership.isActive()) {
return customer.membership.getDiscount();
}
return 0;
}

// Similar functionality with optional chaining (ES6+)
function calculateDiscount(customer) {
return customer?.membership?.isActive() ? customer.membership.getDiscount() : 0;
}

While optional chaining (introduced in ES6) offers a cleaner syntax for safe property access, you can use && for chained function calls. Here, we ensure getDiscount() is only called if customer and its membership are valid and the isActive() function returns true.

Logical OR (||)

The || operator returns the following values:

The first truthy operand: If the first operand evaluates to true, null, or a non-empty string, the expression short-circuits and returns that first operand without evaluating the second operand.The last falsy operand: If all operands are falsy, the expression returns the last falsy operand.

Example 1: OR for Default Values

function getDefaultName(name) {
return name || “Guest”; // Return name if truthy, otherwise “Guest”
}

console.log(getDefaultName(“”)); // Output: Guest (name is empty)
console.log(getDefaultName(null)); // Output: Guest (name is null)
console.log(getDefaultName(“Alice”)); // Output: Alice

Here, name || “Guest” uses short-circuiting. If name is truthy (null or a non-empty string), it short-circuits and returns that value. Otherwise, it returns “Guest”. This ensures a fallback value for cases where a name might not be provided.

Example 2: OR for Conditional Assignments

let age = 0; // Initially undefined

age = age || 18; // Assign 18 if age is undefined or falsy

console.log(age); // Output: 18 (since

Example 3: OR for Short-Circuiting Falsy Evaluations

function hasPermission(user, permission) {
return user.roles.indexOf(permission) !== -1 || user.isAdmin;
}

const user1 = { roles: [“editor”], isAdmin: false };
const user2 = { roles: [“admin”], isAdmin: true };

console.log(hasPermission(user1, “admin”)); // Output: false (no “admin” role)
console.log(hasPermission(user2, “editor”)); // Output: true (either role grants permission)

In this example, hasPermission checks if a user has a specific permission based on their roles or admin status. The || operator allows the function to return true if either condition is met (user has the specific role or is an admin). This simplifies the logic compared to writing separate conditions for each case.

Important Considerations:

Be cautious when using short-circuiting with side effects (operations that modify data or have unintended consequences). If the short-circuiting behavior isn’t intended, use parentheses to force full evaluation.For complex logical expressions, consider using explicit if statements for better readability, especially when dealing with multiple operators.

By effectively utilizing short-circuiting with the && and || operators, you can write more concise, performant, and readable JavaScript code. Remember to use them strategically and thoughtfully to enhance your code’s maintainability and efficiency.

NOTE ON PYTHON:

Python does not support short-circuit evaluation for the and and or operators in the same way that JavaScript does.

Here’s a breakdown:

JavaScript: Both && (AND) and || (OR) operators exhibit short-circuit evaluation. They stop evaluating the entire expression as soon as the outcome is clear based on the first operand.Python: The and and or operators in Python will always evaluate both operands, regardless of the truth value of the first operand.

However, Python offers alternative approaches to achieve similar functionality:

Conditional Expressions:

You can use conditional expressions (ternary operator) to achieve a result based on the first operand’s truth value.

result = condition1 if condition1 else condition2

all() and any() Functions:

all(iterable): Returns True if all elements in the iterable are true. Similar to short-circuiting and in some cases.

any(iterable): Returns True if any element in the iterable is true. Similar to short-circuiting or in some cases.

By understanding these alternatives, you can write Python code that achieves similar logic to short-circuit evaluation in JavaScript.

Short-Circuit Evaluation in JavaScript with && (AND) and || (OR) was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.

​ Level Up Coding – Medium

about Infinite Loop Digital

We support businesses by identifying requirements and helping clients integrate AI seamlessly into their operations.

Gartner
Gartner Digital Workplace Summit Generative Al

GenAI sessions:

  • 4 Use Cases for Generative AI and ChatGPT in the Digital Workplace
  • How the Power of Generative AI Will Transform Knowledge Management
  • The Perils and Promises of Microsoft 365 Copilot
  • How to Be the Generative AI Champion Your CIO and Organization Need
  • How to Shift Organizational Culture Today to Embrace Generative AI Tomorrow
  • Mitigate the Risks of Generative AI by Enhancing Your Information Governance
  • Cultivate Essential Skills for Collaborating With Artificial Intelligence
  • Ask the Expert: Microsoft 365 Copilot
  • Generative AI Across Digital Workplace Markets
10 – 11 June 2024

London, U.K.