20 Feb 2024




Beginner

In JavaScript, null and undefined are both primitive values, but they have different meanings and behaviors.

  1. Undefined: undefined represents a variable that has been declared but has not been assigned a value, or a property that does not exist in an object. When you declare a variable but don't assign a value to it, or when you access a property of an object that doesn't exist, JavaScript automatically assigns undefined to that variable or property.

    Example:

    let x;
    console.log(x); // Output: undefined
    
    let obj = {};
    console.log(obj.prop); // Output: undefined
    
  2. Null: null is used to explicitly represent the absence of any value or object. It is often used to indicate intentional absence of an object value.

    Example:

    let y = null;
    console.log(y); // Output: null
    

In summary:

  • undefined typically indicates a variable that has not been initialized or an object property that does not exist.
  • null typically indicates a deliberate absence of any value or object.

In terms of behavior, null is a value that can be assigned to a variable or returned from a function, whereas undefined usually signifies an uninitialized or non-existent value. However, undefined can also be explicitly assigned to a variable, although this is not a common practice.

javascript
null
undefined