Difference Between undeclared, undefined, and null

Difference Between undeclared, undefined, and null

ยท

1 min read

  1. Undeclared Variable:

    • An undeclared variable is one that has not been declared in the current scope.

    • Attempting to access an undeclared variable will result in a ReferenceError.

Example:

    console.log(brain); // ReferenceError: brain is not defined
  1. Undefined Variable:

    • An undefined variable is one that has been declared but has not been assigned a value.

    • JavaScript initializes declared variables with undefined by default.

Example:

    let heart;
    console.log(heart); // Outputs: undefined
  1. Null Variable:

    • A null variable is one that has been explicitly assigned the value null.

    • It represents the intentional absence of any object value.

Example:

    let soul = null;
    console.log(soul); // Outputs: null

In summary:

  • "Undeclared" means the variable has not been declared or defined in the current scope.

  • "Undefined" means the variable has been declared but not assigned a value, or it can be the default value of uninitialized variables.

  • "Null" means the variable has been intentionally set to a value representing the absence of any object.