Many programming languages have one “non-value” called . It indicates that a variable does not currently point to an object. For example, when it hasn’t been initialized, yet.

    In contrast, JavaScript has two of them: undefined and null.

    Both values are very similar and often used interchangeably. How they differ is therefore subtle. The language itself makes the following distinction:

    • undefined means “not initialized” (e.g. a variable) or “not existing” (e.g. a property of an object).
    • null means “the intentional absence of any object value” (a quote from ).
      Programmers may make the following distinction:

    • undefined is the non-value used by the language (when something is uninitialized etc.).

    • null means “explicitly switched off”. That is, it helps implement a type that comprises both meaningful values and a meta-value that stands for “no meaningful value”. Such a type is called option type or maybe type in functional programming.

    13.2.1. Occurrences of undefined

    Uninitialized variable myVar:

    Parameter x is not provided:

    1. function func(x) {
    2. }

    Property .unknownProp is missing:

    1. assert.equal(obj.unknownProp, undefined);

    If you don’t explicitly specify the result of a function via the return operator, JavaScript returns undefined for you:

    1. assert.equal(func(), undefined);

    13.2.2. Occurrences of null

    The prototype of an object is either an object or, at the end of a chain of prototypes, null. does not have a prototype:

    If you match a regular expression (such as /a/) against a string (such as 'x'), you either get an object with matching data (if matching was successful) or null (if matching failed):

    1. > /a/.exec('x')
    1. > JSON.stringify({a: undefined, b: null})

    Checking for either:

    1. if (x === null) ···

    Does x have a value?

    Is x either undefined or null?

    1. if (x === undefined || x === null) {
    2. }
    3. }

    Truthy means “is true if coerced to boolean”. Falsy means “is if coerced to boolean”. Both concepts are explained properly in .

    undefined and null are the two only JavaScript values where you get an exception if you try to read a property. To explore this phenomenon, let’s use the following function, which reads (“gets”) property .foo and returns the result.

    1. function getFoo(x) {
    2. }

    If we apply getFoo() to various value, we can see that it only fails for undefined and null:

    1. TypeError: Cannot read property 'foo' of undefined
    2. TypeError: Cannot read property 'foo' of null
    3. > getFoo(true)
    4. > getFoo({})
    • Variables with object types are initialized with null.