JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is the difference between null and undefined in JavaScript?

Asked on Jul 18, 2024

Answer

In JavaScript, "null" is an intentional absence of any object value, while "undefined" indicates a variable that has been declared but not yet assigned a value.
// Example of undefined
        let a;
        console.log(a); // Output: undefined

        // Example of null
        let b = null;
        console.log(b); // Output: null
Additional Comment:
  • "undefined" is the default value for variables that are declared but not initialized.
  • "null" is an assignment value that represents no value or no object.
  • Use "null" when you want to explicitly indicate that a variable should be empty.
  • Comparing "null" and "undefined" using "==" results in true, but using "===" results in false because they are of different types.
✅ Answered with JavaScript best practices.
← Back to All Questions