JavaScript
Why does typeof null return “object” in JavaScript?
null is a primitive JavaScript value. The typeof operator returns the string "object" for it because JavaScript retained that behavior from its early implementation. The result tells you what the operator reports. It does not make it safe to read a property from null. MDN’s typeof reference
Predict three results
Imagine a scoreboard that receives a player, a roster, or an empty slot. Predict the output before running these expressions in the browser console.
console.log(typeof { name: "Mira" });
console.log(typeof ["Mira", "Dev"]);
console.log(typeof null);
All three print "object". Arrays are objects and share that result with ordinary object literals. The empty slot is the surprise. If your next line is value.name, the empty slot throws a TypeError. An array usually gives you undefined for the same property, so the two bugs look different on screen.
Ask the narrow questions first
Here is a formatter for those three inputs. Check for the missing value first, then ask whether the input is an array. Only the remaining object branch reads a name. It still validates the name because an object such as {} can be missing that field.
function playerLabel(value) {
if (value === null) return "Open slot";
if (Array.isArray(value)) return value.length + " players";
if (typeof value === "object" && typeof value.name === "string") {
return value.name;
}
return "Unknown player";
}
console.log(playerLabel(null)); // Open slot
console.log(playerLabel(["Mira", "Dev"])); // 2 players
console.log(playerLabel({ name: "Mira" })); // Mira
console.log(playerLabel({})); // Unknown player
Now try playerLabel(undefined). That value takes the final branch because typeof undefined returns "undefined". If the product should show an open slot for both missing values, make that decision explicit in the first condition.
Choose a check that matches the operation
Use value === null when a deliberate empty value has meaning. Use Array.isArray(value) before calling array methods. When you need a player name, check the property you need after ruling out null. A single truthiness check would also catch useful values such as zero or an empty string, which may represent legitimate data elsewhere in the same program.
For a final prediction, try typeof typeof null. The inner result is the string "object", so asking for its type produces "string". That little puzzle is a good way to remember the difference between a value and the text used to describe its type. ECMAScript’s typeof rules