Sobes.tech
Junior

Tell me more about the meanings of null and undefined in JavaScript.

sobes.tech AI

Answer from AI

  • undefined:

    • Implicit value assigned to variables that have been declared but not initialized.
    • Also returned by functions that do not explicitly return a value.
    • This is a primitive data type.
    • The typeof operator returns the string "undefined".
  • null:

    • Explicit value specifically assigned to a variable to indicate the absence of any object.
    • Represents an intentional absence of any object value.
    • This is a primitive data type, but the typeof operator incorrectly returns "object" (a historical bug).
Property undefined null
Origin Implicit (by the system) Explicit (by the developer)
Type Primitive Primitive (although typeof is object)
Value Uninitialized variable Absence of an object
// Example of undefined
let uninitializedVar;
console.log(uninitializedVar); // undefined

function noReturnValue() {
  // no return
}
console.log(noReturnValue()); // undefined
console.log(typeof uninitializedVar); // undefined

// Example of null
let objectVar = null;
console.log(objectVar); // null
console.log(typeof objectVar); // object (historical bug)
Tell me more about the meanings of null and undefined… - sobes.tech