before understanding the differences between undefined and null in javascript we must understand the similarities between them
they belongs 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 false
console.log(!!undefined);//logs false
console.log(Boolean(null));//logs false
console.log(Boolean(undefined));//logs false
ok, let's talk about the difference between undefined & null
undefined is the default value of a variable that has not been assigned a specific value. or a function that no explicit return value ex. console.log(1) or 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 : 'ab',
b: 'bc',
c: 'cd'
}
console.log(_thisIsUndefined);//logs undefined
console.log(doNothing);//logs undefined
console.log(someObj['d']);//logs undefined
null is "a value that represents no value" null is values that has been explicitly defined to a variavle. in this example we get a value of null when the fs.readFile method does not throw an error
fs.readFile('path/to/file',(e,data) => {
console.log(e) // it logs null when no error occurred
if(e){
console.log(e)
}
console.log(data)
})
when comparing null and undefiend we get true when using == and false when using ===
console.log(null == undefined); //logs true
console.log(null === undefined); //logs false
this is it for difference between undefined & null in javascript and stay tuned for more
read more
how to become javascript full stack engineer
Top comments (0)