What is undefined?
In JavaScript, undefined
is a primitive value that represents the absence of a value.
It is one of the two falsy values in JavaScript, the other being null
.
There are a few ways to get an undefined
value:
- Declaring a variable without assigning a value to it:
let x;
console.log(x); // undefined
const obj = {};
console.log(obj.foo); // undefined
function foo() {
console.log(arguments); // undefined
}
foo();
undefined
can be a useful value to check for when you’re not sure if a value has been assigned to a variable or property.
For example, the following code checks if the username
variable has been assigned a value before using it:
let username;
if (username) {
// Do something with the username
} else {
// The username is undefined, so do something else
}
It’s important to note that undefined
is not the same as null
. null
is a falsy value that represents a null object, while undefined
represents the absence of a value.
Conclusion
undefined
is a primitive value in JavaScript that represents the absence of a value. It can be a useful value to check for when you’re not sure if a value has been assigned to a variable or property.