What is the difference between null and undefined in JavaScript?
What is the difference between null and undefined in JavaScript?
267
18-Jun-2024
Updated on 18-Jun-2024
Ravi Vishwakarma
18-Jun-2024In JavaScript, null and undefined are both values that represent the absence of a value, but they have distinct meanings and uses.
Here's a detailed comparison between the two:
It's type is ‘undefined’.
typeof undefined; // “undefined”It's type is ‘object’.
typeof null; // ‘object’Automatically assigned to variables that are declared but not initialized.
Explicitly assigned to variables to represent "no value".
Commonly used to reset or clear variables.
undefinedandnullare not strictly equal because they are different types.undefinedandnullare loosely equal because they both represent an absence of value.undefinedcan sometimes be a result of not properly initializing a variable.nullis used intentionally and explicitly.Note:
undefinedgenerally indicates that a variable has been declared but not yet assigned a value, whilenullis an assignment value that can be used to represent no value intentionally.