?? Back to Basics in JavaScript: True, False, and Operators ??
JavaScript can be quirky, especially regarding truthy, falsy, and those operators you think you know — ||, &&, and !== Let’s clear the air with some fundamentals and insights. ?
?? What’s “True” and “False” in JS?
In JavaScript: ?
?? Good to know:
?? || (OR): Returns the first truthy value it finds. If all are falsy, it returns the last value. ?
?? Example: '' || 'default' → 'default' ?
?? && (AND): Returns the first falsy value. If all values are truthy, it returns the last truthy value. ?
?? Example: 1 && 'hello' && 0 → 0 ?
?? !== (Not Equal - Strict): Checks both value and type. ?
?? Example: 0 !== '0' → true ?
The Difference Between === and ==:?
?? === (Strict Equality): Compares both value and type. ?
?? Example: 0 === '0' → false ?
?? == (Loose Equality): Allows type coercion, which can lead to unexpected results. ?
?? Example: 0 == '0' → true ?
Best Practice: Always use === (or !==) unless you specifically want type coercion. Strict equality makes your code more predictable and less error-prone. ?
?? Common Gotchas and Unexpected JS Behavior:
?? Falsy vs Truthy Edge Cases:
- [] and {} are truthy, but null and undefined are falsy. ?
?? Example: if ([]) { console.log('This runs!'); } ?
?? Empty String vs Space:?
- '' → falsy, but ' ' (a string with a space) → truthy. ?
?? Example: ' ' && 'valid' → 'valid' ?
?? Type Coercion with ==:
- Numbers and strings can be compared loosely, often leading to confusion. ?
?? Example: 0 == '0' → true ?
?? Example: null == undefined → true ?
?? NaN is “Not Equal to Itself”:
?? Example: NaN === NaN → false ?
Tip: Use Number.isNaN(value) to check for NaN. ?
?? 0 and -0 are equal, but not always identical:
?? Example: Object.is(0, -0) → false ?
?? Logical Operators Short-Circuiting:
?? - With ||, if the first value is truthy, the rest of the expressions are ignored. ?
?? Example: true || console.log('This won’t run'); ?
?? - With &&, if the first value is falsy, the rest of the expressions are ignored. ?
?? Example: false && console.log('This won’t run'); ?
?? Real-life Use Cases:
?? Default Values Safely:?
const userName = inputName || 'Guest'; // Fallback to 'Guest' if falsy ?
?? Conditional Execution Without Errors:?
if (data && data.length) { ? console.log('Data exists and is not empty'); }
?? Strict Type Comparisons:?
if (value !== null && value !== undefined) { ? console.log('Value exists'); }
?? The double negation operator (!!)
It is used to convert a value into its boolean equivalent (true or false).
How it works:
?? - Truthy → false ?
?? - Falsy → true ?
?? - Truthy → true
?? - Falsy → false ?
领英推荐
?? Why use !!?
!! is a concise way to ensure a value is strictly a true or false boolean, rather than relying on its truthy/falsy behavior in conditions.
Examples: ?
!!0? ? ? ? // false (0 is falsy)
!!1? ? ? ? // true (1 is truthy)
!!'' ? ? ? // false (empty string is falsy)
!!'hello'? // true (non-empty string is truthy)
!!null ? ? // false
!!undefined // false
!![] ? ? ? // true (empty array is truthy)
!!{} ? ? ? // true (empty object is truthy)
?? Common Use Cases:
?? Converting values to booleans explicitly:
const isValid = !!inputValue; ?
console.log(isValid); // true or false depending on inputValue
?? Checking for the presence of a value:
if (!!user) { ?
? console.log('User exists'); ?
}
?? Short-circuiting logic where a boolean is needed:
const isLoggedIn = !!userToken; // Ensure it's a boolean
Note: While Boolean(value) achieves the same result as !!, the double negation is shorter and more common in JavaScript codebases.
?? Now you know — !! is your go-to tool for quickly converting anything into a clear boolean value! ?
?? The Nullish Coalescing Operator (??)
?? What is ???
The?? operator (introduced in ES2020) provides a default value only when the left-hand operand is null or undefined.
const result = value ?? defaultValue;
?? How is ?? different from ||?
While || considers all falsy values (e.g., 0, '', false) a reason to fallback,?? only triggers the fallback when the value is null or undefined.
const name = '' || 'Default Name';? // 'Default Name' ('' is falsy)
const name2 = '' ?? 'Default Name'; // '' ('' is not null or undefined)
const count = 0 || 10;? // 10 (0 is falsy)
const count2 = 0 ?? 10; // 0 (0 is valid, not null/undefined)
?? When to Use ??
const userInput = null;
const finalValue = userInput ?? 'Default Value';
console.log(finalValue); // 'Default Value'
Combine ?? with optional chaining to handle missing or undefined values safely:
const user = { profile: null };
const profileName = user.profile?.name ?? 'Anonymous';
console.log(profileName); // 'Anonymous'
JavaScript can feel like a wild ride — what’s your favorite trick, gotcha, or “aha!” moment with truthy/falsy values and logical operators? Share your insights or experiences below ??
Let’s discuss and demystify JS together ?? ?
#JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #BackToBasics #LearnToCode ?