Member-only story
What is the Difference Between Null and Undefined in JavaScript?
In JavaScript, null and undefined are two special values that represent the absence of a value. However, they have different meanings and use cases.
Undefined: Undefined is a built-in value in JavaScript, which is assigned to a variable that is declared but has not been assigned a value. For instance:
let variable;
console.log(variable); // undefined
In the above example, the variable is declared, but it has not been assigned a value. When you try to access its value, it returns undefined. In JavaScript, undefined is also returned when you try to access a property or a method of an object that does not exist.
let obj = {};
console.log(obj.property); // undefined
console.log(obj.method()); // TypeError: obj.method is not a function
Null: Null is another built-in value in JavaScript, which represents the intentional absence of any object value. It is often used to assign an empty or non-existent value to an object or a variable.
let variable = null;
console.log(variable); // null
In the above example, the variable is assigned a value of null, which indicates that it intentionally does not have any value. Unlike undefined, null is explicitly assigned to a variable, property, or method.