What is the difference between null and undefined in JavaScript?

In JavaScript, null and undefined are both special values that represent the absence of a meaningful value.

However, there are some key differences between them:

  1. undefined is a value that a variable can have if it has been declared but has not been assigned a value. It is also the default return value for a function that does not return anything.

    For example:

    let x; // x is undefined
    function myFunction() {} // myFunction returns undefined
  2. null, on the other hand, is a value that represents the intentional absence of any object value. It is often used to indicate that a variable or property should have no value.

    For example:

    let y = null; // y has no value
    let obj = { prop: null }; // obj.prop has no value
  3. Another difference is that undefined is a primitive value, whereas null is an object. This means that null is actually a special case of object, whereas undefined is its own primitive type.

  4. Finally, it is important to note that undefined and null are both falsy values in JavaScript, meaning that they will be coerced to false in a boolean context.

    For example:

    if (!undefined) {
      console.log("dont print");
    }
    
    if (!null) {
      console.log("dont print this one also");
    }

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: