While debugging your code and ended up staring at undefined like it owes you money? Or tried { } + [] and your console laughed at you? Yeah… JavaScript loves trolling developers. Let’s fix that once and for all.
undefined vs Missing Property
Let’s start with an example:
const user = {
username: "rahul123",
phone: undefined
};
console.log(user.username); // "rahul123"
console.log(user.phone); // undefined
console.log(user.email); // undefined
console.log("phone" in user); // true
console.log("email" in user); // false
Here’s what’s going on:
-
usernameexists and has a value, so it prints"rahul123" -
phoneexists but is empty, so it printsundefined -
emaildoesn’t exist, so it also printsundefined -
"in"checks if a property actually exists
Tip: Don’t use if(!user.phone) to check if a property exists. That can give false results. "in"is safer.
Real-Life Example: Shopping Cart
const cart = {
itemCount: 0,
coupon: undefined
};
console.log(cart.itemCount); // 0
console.log(cart.coupon); // undefined
console.log(cart.discount); // undefined
Quick takeaways:
-
itemCountexists but is 0. If you checkif(!cart.itemCount)it will look false, even though the property exists -
couponexists but is empty, printsundefined -
discountdoesn’t exist, printsundefined
Always check property existence properly to avoid mistakes.
The { } + [] Mystery in JavaScript
console.log({} + []); // "[object Object]"
console.log([] + {}); // "[object Object]"
console.log([] + []); // ""
console.log({} + {}); // NaN
What’s happening here:
-
{ } + []→ JavaScript sometimes treats{}as a code block. Use( {} ) + []if you want"[object Object]" -
[] + {}→ array converts to string""plus object string"[object Object]"→"[object Object]" -
[] + []→ two empty strings →"" -
{ } + {}→ object + object →NaN
JavaScript type conversion can be confusing. Keep an eye on it.
Quick Cheat Sheet
| Expression | Output | Why |
|---|---|---|
user.phone exists & undefined |
undefined | Property exists but empty |
user.email missing |
undefined | Property doesn’t exist |
"phone" in user |
true/false | Checks existence |
{ } + [] |
"[object Object]" | Object converted to string |
[] + {} |
"[object Object]" | Array string + object string |
[] + [] |
"" | Empty + empty |
{ } + {} |
NaN | Object + object numeric addition |
Why This Matters
Knowing these little quirks helps you:
- Save hours debugging your code
- Avoid tricky JavaScript bugs
- Feel confident working with objects and arrays
Wrap objects in parentheses when adding or concatenating:
( {} ) + []
Also, check properties with "in" or hasOwnProperty() so you don’t get surprises.
Top comments (0)