What is Undefined in JavaScript?
In JavaScript, the undefined
keyword represents the primitive value that is assigned to variables that have not been assigned a value. It is also the initial value of all global variables.
How to Check for Undefined
You can use the typeof
operator to check if a variable is undefined
. For example:
const myVariable;
console.log(typeof myVariable); // "undefined"
When to Use Undefined
You should use undefined
when you want to indicate that a variable has not been assigned a value. For example, you might use undefined
as the default value for a function parameter.
Example
The following code shows how to use undefined
as the default value for a function parameter:
function myFunction(param = undefined) {
console.log(param);
}
myFunction(); // "undefined"
Conclusion
Undefined
is a primitive value in JavaScript that represents a variable that has not been assigned a value. You can use the typeof
operator to check if a variable is undefined
. You should use undefined
when you want to indicate that a variable has not been assigned a value.