// Parentheses around the condition are requiredif (user.isAdmin) { showAdminPanel();}// Python doesn't require them// if user.is_admin:// show_admin_panel()
Everything else is truthy — including some surprises:
Copy
if ("hello") // true — any non-empty stringif (42) // true — any non-zero numberif ([]) // true — empty array!if ({}) // true — empty object!
Empty arrays [] and empty objects {} are truthy in JavaScript. This is different from Python, where empty lists and dicts are falsy. To check if an array is empty, use array.length === 0.
// Check if a variable has a useful valueconst username = getUserInput();if (username) { console.log(`Hello, ${username}`);} else { console.log("Please enter a username");}// Check if an array has itemsconst users = await fetchUsers();if (users.length) { // 0 is falsy, any other number is truthy renderUserList(users);} else { renderEmptyState();}
Keep ternaries simple — one condition, two outcomes. If you need more complex logic, use an if/else block or extract the logic into a separate function.
Returns the right side only if the left is null or undefined. Doesn’t trigger on 0, "", or false.
Copy
const count = 0;console.log(count || 10); // 10 — treats 0 as falsyconsole.log(count ?? 10); // 0 — only falls back on null/undefinedconst name = "";console.log(name || "Anonymous"); // "Anonymous" — treats "" as falsyconsole.log(name ?? "Anonymous"); // "" — only falls back on null/undefined
Use ?? when a value of 0, "", or false is valid and shouldn’t be replaced. Use || when you want any falsy value to trigger the fallback.