Interview question
What is the difference between null and undefined in JavaScript? JavaScript में null और undefined में क्या अंतर है?
Answer
| Aspect | null | undefined |
|---|---|---|
| Type | Object (due to a bug) | undefined |
| Meaning | Intentional absence of a value | Unintentional absence of a value |
| When assigned | By programmer explicitly | By JavaScript automatically |
| Examples | let x = null; | let x; or function(param) { } |
// undefined
let a; // declared but not assigned
console.log(a); // undefined
function test(param) {
console.log(param); // undefined if not passed
}
test();
// null
let b = null; // explicitly assigned
console.log(b); // null
// Comparison
console.log(null == undefined); // true (loose equality)
console.log(null === undefined); // false (strict equality)
console.log(typeof null); // 'object' (famous bug!)
console.log(typeof undefined); // 'undefined'Interview tip: Explain that null is intentional (developer sets it) while undefined is unintentional (JavaScript sets it). Also mention the famous bug: typeof null === 'object'.
| Aspect | null | undefined |
|---|---|---|
| Type | Object (एक bug है) | undefined |
| Meaning | Intentional absence | Unintentional absence |
| Assign कौन करता है | Programmer explicitly | JavaScript automatically |
| Examples | let x = null; | let x; or function(param) |
// undefined
let a; // declared पर not assigned
console.log(a); // undefined
function test(param) {
console.log(param); // undefined अगर pass न हो
}
test();
// null
let b = null; // explicitly assigned
console.log(b); // null
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(typeof null); // 'object' (bug!)
console.log(typeof undefined); // 'undefined'इंटरव्यू टिप: समझाएं null intentional है (developer sets करता है) जबकि undefined unintentional है (JavaScript sets करता है)। typeof null === 'object' का ज़िक्र करें।
Was this answer clear?