What's the difference between `undefined` and `null`?
Before understanding the differences between undefined and null we must understand the similarities between them.
- They belong to JavaScript's 7 primitive types.
let primitiveTypes = ['string', 'number', 'null', 'undefined', 'boolean', 'symbol', 'bigint'];
- They are falsy values. Values that evaluated to false when converting it to boolean using
Boolean(value)
or!!value
.
console.log(!!null); //logs falseconsole.log(!!undefined); //logs falseconsole.log(Boolean(null)); //logs falseconsole.log(Boolean(undefined)); //logs false
Ok, let's talk about the differences.
undefined
is the default value of a variable that has not been assigned a specific value. Or a function that has no explicit return value ex.console.log(1)
. Or a property that does not exist in an object. The JavaScript engine does this for us the assigning of undefined value.
let _thisIsUndefined;const doNothing = () => {};const someObj = {a: 'ay',b: 'bee',c: 'si',};console.log(_thisIsUndefined); //logs undefinedconsole.log(doNothing()); //logs undefinedconsole.log(someObj['d']); //logs undefined
null
is "a value that represents no value".null
is value that has been explicitly defined to a variable. In this example we get a value ofnull
when thefs.readFile
method does not throw an error.
fs.readFile('path/to/file', (e, data) => {console.log(e); //it logs null when no error occurredif (e) {console.log(e);}console.log(data);});
When comparing null and undefined we get true when using == and false when using ===.
console.log(null == undefined); // logs trueconsole.log(null === undefined); // logs false
October 24, 2022
3293
Read more
What is the JavaScript += Operator and How Do You Use It?
December 04, 2022
JavaScriptUsing the startsWith() Method in JavaScript
December 04, 2022
JavaScriptReverse a String in JavaScript: 2 Easy Methods
December 02, 2022
JavaScript