Junior — Middle
Explain the differences between null and undefined in programming language.
sobes.tech AI
Answer from AI
In JavaScript (and Node.js), null and undefined are two different types that are often confused, but they have different meanings:
- undefined is the default value for variables that have been declared but not initialized. Also, a function without an explicit return statement returns undefined.
- null is an explicit assignment of a value, meaning "no value" or "empty value".
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
function foo() {}
console.log(foo()); // undefined — function does not return anything
The key difference is that undefined usually means that a value has not been assigned, whereas null is an intentional indication of the absence of a value.