DEV Community

Cover image for What is difference between undefined & null in javascript ? 🚀 🚀
Ashish donga
Ashish donga

Posted on • Updated on

What is difference between undefined & null in javascript ? 🚀 🚀

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'];
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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)
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

this is it for difference between undefined & null in javascript and stay tuned for more

read more

how to become javascript full stack engineer

7 killer JavaScript One-Liners You Must Know

Top 7 best Algorithms to Improve your JavaScript Skills

Top comments (0)