Middle
What is the difference between null and undefined?
sobes.tech AI
Answer from AI
In JavaScript, null and undefined are two different types that both denote the absence of a value but are used in different contexts.
undefinedis the default value for variables that have been declared but not initialized, as well as for missing object properties or function arguments.nullis an explicit assignment of a value, meaning "no value" or "empty value." It is usually used by programmers to indicate the intentional absence of an object.
Example:
let a;
console.log(a); // undefined — variable declared but not initialized
let b = null;
console.log(b); // null — variable explicitly assigned an empty value
let obj = {};
console.log(obj.prop); // undefined — property does not exist in the object
Thus, undefined is a default state, while null is an explicit indication of the absence of a value.