What is undefined vs not defined in JavaScript?
The key difference between undefined and not defined is that undefined refers to a variable that has been declared but not assigned a value, while not defined refers to a variable that hasn’t been declared in the code at all. Accessing an undefined variable returns the value undefined, but trying to access a not defined variable throws a ReferenceError
Suppose you're at a restaurant and ask for dessert but don’t specify which one—this is like undefined because the request exists but has no value. If you never mention dessert at all, it’s like not defined, leading to confusion (or an error) when the waiter tries to serve something you didn’t order.
What is undefined?
In JavaScript, a variable is undefined when it has been declared but not assigned a value. This state indicates that the variable exists in memory but doesn’t hold any meaningful value yet.
Examples of undefined
Declared but not assigned:
Here, myVar is declared but not initialized, so JavaScript assigns it the undefined.
Try assigning null to myVar instead of leaving it uninitialized. How does the output change?
Missing object property:
The property age does not exist in the person object, so accessing it returns undefined.
Function without a return statement:
A function that doesn’t explicitly return a value returns undefined by default.
While undefined indicates an existing variable without a value, not defined takes it a step further to represent variables that don’t exist at all. Let’s explore this concept.
What is not defined?
In JavaScript, a variable or property is considered not defined when it hasn’t been declared at all in the current ReferenceError.
Examples of not defined
Accessing undeclared variables:
The variable nonExistentVar hasn’t been declared anywhere in the code, leading to an error.
Misspelled variable names:
JavaScript is case-sensitive, so myVariable and myvariable are treated as different variables.
Accessing properties of an undeclared object:
Here, the object myObject is not declared, causing an error.
Key differences between undefined and not defined
Ready to learn JavaScript and build interactive web applications? Start our Learn JavaScript course and gain a solid foundation, preparing you for a career in web development.
Want to become a full-stack web developer? Begin our Become a Full Stack Developer skill path, starting with the basics and advancing to expert-level skills, setting you up for success in the world of full-stack development.
Key takeaways
undefined: A variable or property exists but lacks a value.not defined: A variable or property does not exist in the code, resulting in an error when accessed.Always declare variables before using them to avoid
ReferenceError.Avoid assigning
undefinedmanually; let JavaScript handle it.Use tools like linters to catch undeclared variables or typos.