undefined vs not defined
These two sound alike but mean completely different things. Confusing them is one of the most common beginner mistakes.
undefined means memory was allocated but no value assigned yet. not defined means the variable was never declared anywhere. typeof is the safe way to check.
EXERCISE
1undefined: Memory Reserved, Value Pending
When JavaScript says a variable is undefined, it does not mean the variable does not exist. It means memory was reserved, but nobody filled it with a value yet.
undefined is a value. That sentence does more work than it looks like it does, because most of the confusion around it comes from people treating it as an error or as nothing at all. It is neither. It is a real value that puts in a slot to mean this name exists and nothing has been assigned to it yet.
You can check its type, store it, pass it to a function and compare against it, exactly like any other value:
var pending;
console.log(pending); // undefined
console.log(typeof pending); // "undefined"
console.log(pending === undefined); // true
There are three separate ways a value ends up as undefined, and knowing which one you are looking at tells you where the bug is.
A declared variable before its assignment, which is the case above, and also every var read before its line runs.
A property that does not exist on an object:
var user = { name: "Ada" };
console.log(user.name); // "Ada"
console.log(user.email); // undefined
Asking for a missing property is not an error. The object simply does not have it, and JavaScript answers with undefined rather than throwing. That is convenient right up until a typo in a property name gives you undefined instead of telling you the name was wrong.
A function that returns nothing:
function logIt(value) {
console.log(value);
}
var result = logIt("hi");
console.log(result); // undefined
logIt has no return, so calling it produces undefined. The function did its job; there was simply no value to hand back.
All three are ordinary behaviour, not failure. What makes undefined worth this much is the contrast coming in the next exercise: there is a second state that looks similar in a console and behaves completely differently, and mixing them up sends you looking in the wrong place.
One more source worth knowing, because it looks like a bug the first time you meet it:
function greet(name, greeting) {
console.log(greeting + ", " + name);
}
greet("Ada"); // "undefined, Ada"
A parameter you do not pass is not an error. It is declared by the function signature, so it has a slot, and the slot is empty: undefined again. JavaScript will happily concatenate that into a string and show it to someone. Default parameter values exist precisely to close this gap:
function greet(name, greeting = "Hello") {
console.log(greeting + ", " + name);
}
greet("Ada"); // "Hello, Ada"
EXERCISE
2not defined: No Memory, No Existence
If undefined means "the slot exists but is empty", then not defined means "there is no slot at all". JavaScript has never heard of this variable.
not defined is not a value. It is an error, thrown when you read a name that was never declared anywhere in scope. The memory phase never created a slot for it, so there is nothing to hand back, not even undefined.
console.log(mystery); // ReferenceError: mystery is not defined
Put the two side by side and the distinction becomes concrete. One name has a slot and no value; the other has no slot at all:
var declared;
console.log(declared); // undefined
console.log(notDeclared); // ReferenceError: notDeclared is not defined
The first line prints and execution continues. The second stops the program. That difference matters more than the wording: an undefined flows quietly through your code and surfaces somewhere later as NaN or [object Undefined] in a user-visible string, while a ReferenceError fails immediately at the line that caused it.
So the two states point you in opposite directions when . undefined means you spelled the name correctly and the value was never set, so look at what was supposed to assign it. ReferenceError means the name itself is wrong, or out of scope, or the file that declares it did not load.
There is one way to ask about a name without risking the error. typeof is the only operator that tolerates an undeclared name:
if (typeof maybeThere === "undefined") {
console.log("not available");
}
This does not throw, whether maybeThere was declared and left empty or never declared at all. That tolerance is occasionally useful for feature detection, and it is also why typeof is the wrong tool for checking your own variables: it silently accepts the typo you were hoping to catch.
Pro Tip: A third message,
TypeError: x is not a function, is neither of these. It means the slot exists, holds something that is not callable, usuallyundefined, and you put parentheses after it. Three different messages, three different causes, and reading them precisely saves more time than any debugger.
EXERCISE
3Loosely Typed: Freedom and Risk
JavaScript does not lock a variable to one type. You can store a number, then replace it with a string, then replace it with a boolean. That is called a loosely typed (or weakly typed) language.
JavaScript is loosely typed, which means a variable is not tied to a kind of value. The same name can hold a number, then a string, then an object, and nothing complains. The type belongs to the value, not to the variable.
var thing = 42;
console.log(typeof thing); // "number"
thing = "forty-two";
console.log(typeof thing); // "string"
thing = { value: 42 };
console.log(typeof thing); // "object"
The upside is obvious: less ceremony, fewer declarations, faster to write. The cost is that a wrong type is not caught when you write it, or when the file loads. It is caught when something finally tries to use the value, which can be much later and somewhere unrelated.
This is where undefined becomes genuinely dangerous rather than merely untidy, because it participates in operations instead of stopping them:
var price;
console.log(price + 10); // NaN
console.log("Total: " + price); // "Total: undefined"
console.log(price * 2); // NaN
None of those three lines throws. The first and third produce NaN, which then spreads through every calculation that touches it. The second produces a string that will be rendered to a user, on a page, in production, reading Total: undefined. The mistake happened wherever price was supposed to be set; the symptom appears wherever the value is finally used, and those two places can be in different files.
The habit worth forming is to check before you use, at the boundary where a value arrives:
function total(price, qty) {
if (typeof price !== "number" || typeof qty !== "number") {
throw new Error("total() needs two numbers");
}
return price * qty;
}
That turns a silent NaN that surfaces three functions later into a loud failure at the point the bad value entered. Loose typing is not a flaw to work around, but it does move the responsibility for type checking from the language to you, and the cheapest place to accept that responsibility is the edge of your own functions.
