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); // undefinedfunction test(param) { console.log(param); // undefined if no argument is passed}let c = undefined;console.log(c); // undefinedlet d = {};console.log(d.fake); // undefinednull
- 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); // nullconsole.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 definedPractical 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(); // hiWe can also supply a parameter to overwrite this default:
logHi('bye'); // byeWith default parameter, undefiend will use the default while null does not.
logHi(undefined); // hilogHi(null); // null