Intern
What are undefined variables in JavaScript?
sobes.tech AI
Answer from AI
Undefined variables are variables that have not been assigned any value after their declaration. JavaScript automatically assigns the value undefined to such variables. This value can also be explicitly assigned.
Examples:
// Declaration without assignment
let myVariable;
console.log(myVariable); // Outputs undefined
// Explicit assignment of undefined
let anotherVariable = undefined;
console.log(anotherVariable); // Outputs undefined
// Accessing a non-existent property of an object
const myObject = {};
console.log(myObject.nonExistentProperty); // Outputs undefined
undefined is a primitive value that differs from null. null is usually used to explicitly indicate the absence of a value or emptiness, whereas undefined means no assigned initial value.
Comparison of undefined and null:
| Property | undefined | null |
|---|---|---|
Type with typeof |
"undefined" | "object" (historical mistake) |
| Assignment | Automatically upon declaration without a value; can be explicitly assigned | Must be explicitly assigned |
| Purpose | Absence of an assigned initial value | Explicit absence of a value, "emptiness" |
Checking for undefined can be done using the strict equality operator (===) or the loose (==), although strict is more reliable and avoids type coercion. You can also use typeof.
let value;
if (value === undefined) {
console.log("Value is undefined");
}
if (typeof value === "undefined") {
console.log("Type is undefined");
}