Junior
Can you tell more about the differences between null and undefined in JavaScript?
sobes.tech AI
Answer from AI
-
undefined:- Assigned to variables that have been declared but not initialized with a value.
- It is the default value for function parameters that are not passed arguments.
- Occurs when trying to access a non-existent property of an object or an array element.
- Data type —
undefined.
-
null:- A special value explicitly assigned to a variable to indicate "absence of a value".
- Represents the intentional absence of any object or primitive value.
- Data type —
object(this is a historical JavaScript error, but it is so).
Main differences in the table:
| Characteristic | undefined |
null |
|---|---|---|
| Origin | Implicit (by default) | Explicit (assigned by the developer) |
| Purpose | Declared but not assigned a value | Intentional absence of a value |
Data type (typeof) |
undefined |
object |
| Boolean context | false |
false |
Equality (==) |
null == undefined (true) |
null == undefined (true) |
Strict equality (===) |
null === undefined (false) |
null === undefined (false) |
Example:
let a; // Declared but not initialized -> undefined
console.log(a); // undefined
const obj = {};
console.log(obj.prop); // Accessing a non-existent property -> undefined
function greet(name) {
console.log(name);
}
greet(); // Parameter name not passed -> undefined
let b = null; // Explicitly assigned null
console.log(b); // null
let c = {};
c.data = null; // Property data assigned null
console.log(c.data); // null
console.log(typeof a); // undefined
console.log(typeof b); // object
console.log(null == undefined); // true
console.log(null === undefined); // false