3 min read
•Question 47 of 50easyWhat is Short-Circuit Evaluation?
Understanding logical operators and evaluation.
What You'll Learn
- && and || behavior
- Default values pattern
- Guard clauses
How It Works
code.jsJavaScript
// && - returns first falsy or last truthy
true && 'hello'; // 'hello'
false && 'hello'; // false
'a' && 'b' && 'c'; // 'c'
// || - returns first truthy or last falsy
null || 'default'; // 'default'
'value' || 'default'; // 'value'
0 || 'default'; // 'default'Default Values
code.jsJavaScript
// Using ||
function greet(name) {
name = name || 'Guest';
console.log('Hello, ' + name);
}
greet('John'); // 'Hello, John'
greet(); // 'Hello, Guest'
// Problem: falsy values
greet(''); // 'Hello, Guest' (oops!)
// Solution: Nullish coalescing (??)
function greet(name) {
name = name ?? 'Guest';
console.log('Hello, ' + name);
}
greet(''); // 'Hello, ' (correct)Guard Clauses
code.jsJavaScript
// Conditional execution with &&
const user = { name: 'John' };
user && console.log(user.name); // 'John'
null && console.log('wont run'); // null
// Optional function call
const callback = null;
callback && callback(); // doesn't throw
// Better: optional chaining
callback?.();Assignment
code.jsJavaScript
// ||= assigns if falsy
let a = null;
a ||= 'default'; // a = 'default'
// &&= assigns if truthy
let b = 'value';
b &&= 'new'; // b = 'new'
// ??= assigns if null/undefined
let c = 0;
c ??= 'default'; // c = 0 (not changed)