undefined vs not defined in JavaScript
JavaScript handles variables in a unique way compared to many other programming languages, especially regarding the concepts of undefined and not defined.
What is undefined?
In JavaScript, undefined is a special keyword and primitive value. It is automatically assigned to variables that have been declared but not yet given a value.
Why does this happen?
- When JavaScript code runs, it first creates a global execution context.
- During this process, JavaScript allocates memory for all variables and functions before any code is executed (this phase is called hoisting).
- For variables, JavaScript sets their initial value to
undefinedas a placeholder until they are assigned a real value.
console.log("a =", a); // Output: a = undefined
var a = 10;
console.log("a =", a); // Output: a = 10
Explanation
ais declared withvar. Before the value10is assigned,aexists in memory with the valueundefined.- After the assignment,
aholds the value10.
What is not defined?
A variable is not defined when you try to access a variable that has never been declared in your code.
Explanation
x has not been declared anywhere in the code. Trying to access it causes a ReferenceError.
Key Differences
undefined |
not defined |
|
|---|---|---|
| When? | Variable declared but unassigned | Variable never declared |
| Error? | No error; value is undefined |
ReferenceError when accessed |
| Example | var a; console.log(a); // undefined |
console.log(x); // ReferenceError: x is not defined |
Common Mistake: Assigning undefined
It's possible to assign undefined to a variable:
However, this is generally considered bad practice because:
undefinedis meant as a placeholder before a variable is assigned a value.- Assigning
undefineddirectly might make your code harder to understand and can lead to bugs or confusion.
Quick FAQs
-
Is
undefinedthe same as "empty"?
No. An
undefinedvariable has memory reserved for it; it's not the same as empty or non-existent. -
What if I declare a variable but never assign a value?
It will hold the value
undefinedfor its entire lifetime. -
Should I use
undefinedas a value on purpose?
Best practice is to let JavaScript use
undefinednaturally rather than assigning it yourself.
Key Takeaway
undefined: Variable declared, memory reserved, but not yet assigned a value.not defined: Variable does not exist in the current scope; accessing it throws aReferenceError.- Avoid directly assigning
undefinedto variables.