All Interview Questions
About Lesson

Q4 What’s the difference between a variable that is: null, undefined or undeclared?

Ans:

In JavaScript, variables can be in different states such as null, undefined, or undeclared. Each state has distinct characteristics and implications. Let’s explore the differences:

null

  • Type: object
  • Meaning: Represents the intentional absence of any object value.
  • Usage: Explicitly assigned to indicate that a variable has no value.
  • Example:
let a = null;
console.log(a); // Output: null
console.log(typeof a); // Output: object

undefined

  • Type: undefined
  • Meaning: Indicates that a variable has been declared but has not been assigned a value.
  • Usage: This is the default value for uninitialized variables or object properties that do not exist.

Example

let b;
console.log(b); // Output: undefined
console.log(typeof b); // Output: undefined

let obj = {};
console.log(obj.someProperty); // Output: undefined
undeclared
  • Type: Not defined
  • Meaning: A variable that has not been declared in the current scope.
  • Usage: Referring to an undeclared variable results in a ReferenceError.
  • Example
try {
    console.log(c); // Throws a ReferenceError
} catch (e) {
    console.log(e); // Output: ReferenceError: c is not defined
}

© GeekySanjay