What is the difference between the values
When a variable has been declared but not yet assigned a value, it will have the type and value
let myVar; console.log(myVar); // will print "undefined" console.log(typeof myVar); // will also print "undefined"
When a variable has not been declared or assigned, it will also be of type
undefined and throw a
ReferenceError when accessed. Therefore,
typeof will produce the same result for declared but undefined variables and undeclared variables.
console.log(undeclaredVar); // will throw a ReferenceError console.log(typeof undeclaredVar); // will print "undefined"
null is a value that represents nothing. Think of
null as an empty container and
undefined as the absence of a container. A variable will only have the value
null when it is explicitly assigned, and will be of type
const myVar = null; console.log(myVar); // will print "null" console.log(typeof myVar); // will print "object"
The difference between
undefined are considered the same when using loose equality (
==) but not when using strict equality (
console.log(undefined == null); // will print "true" console.log(undefined === null); // will print "false"