What is the difference between null, undefined, and undeclared in JavaScript?
JavaScriptundefined
- A variable has been declared but no value has been assigned to it
- It's the default value of function parameters and variables that are declared but not initialized
let x;
console.log(x); // undefined
function test(param) {
console.log(param); // undefined if no argument is passed
}
let c = undefined;
console.log(c); // undefined
let d = {};
console.log(d.fake); // undefined
null
- Represents an intentional absence of any object value
- It's a primitive value that represents "nothing", "empty" or "value unknown"
- Must be explicitly assigned
let user = null;
console.log(user); // null
console.log(typeof null); // "object" (this is a known JavaScript quirk)
undeclared
- Variables that don't exist and haven't been declared with var, let, or const
- Trying to access them throws a ReferenceError
console.log(nonExistentVariable);
// Throws ReferenceError: nonExistentVariable is not defined
Practical difference between undefined and null
let logHi = (str = "hi") => {
console.log(str);
};
The code above creates a function named logHi. This function requires one parameter and sets the default of that parameter to hi if it isn’t supplied. Here’s what that looks like:
logHi(); // hi
We can also supply a parameter to overwrite this default:
logHi("bye"); // bye
With default parameter, undefiend will use the default while null does not.
logHi(undefined); // hi
logHi(null); // null
00:00