断言对象属性存在却得到意外结果的问题排查
Hey there! Let's break down why your code always lands in the else branch and get it working as you expect.
The Core Issue
Your current condition checks if user.fName === true and user.lName === true—but those properties hold string values ('john' and 'doe'), not the boolean true. JavaScript's strict equality (===) only matches values that are identical in both type and content, so these checks will never pass, no matter what valid names you use.
How to Fix It
Instead of comparing to true, we need to verify that these properties exist and have a meaningful value. Here are two reliable approaches:
1. Simple Truthy Check (Great for Most Scenarios)
Non-empty strings, positive numbers, and defined values are "truthy" in JavaScript—they evaluate to true when used in a boolean context. You can simplify your condition to:
if(user.fName && user.lName && user.age >= 18) { // Success case }
This works because:
user.fNameis'john'(truthy)user.lNameis'doe'(truthy)user.ageis18(meets the>=18requirement)
2. Strict Existence + Value Check (More Precise)
If you want extra safeguards—like ensuring properties exist on the object and aren't empty strings—you can use this stricter version:
if('fName' in user && 'lName' in user && user.fName.trim() !== '' && user.lName.trim() !== '' && user.age >= 18) { // Success case }
This guards against edge cases where fName might be an empty string or the property doesn't exist at all.
Corrected Full Code
Here's your code updated with the simple truthy check:
let user = { fName: 'john', lName: 'doe', uName: 'jDoe23', age: 18, }; function helloUser(user) { if(user.fName && user.lName && user.age >= 18) { console.log(`Hello ${user.uName}. Welcome to the world of wonders.`); } else { console.log("Please get a parent's permission before playing this game."); } }; helloUser(user);
Now when you run this, it'll trigger the welcome message just like you wanted!
内容的提问来源于stack exchange,提问作者Mr Neptune

