The Non-Value Trio of JavaScript

Undefined, Null, and NaN are 3 keywords, known as non-values or empty values, that are often a source of buggy code, stress, and confusion for many beginning JavaScript engineers. Part of the reason for that is that they are seldom given the proper attention they merit in most courses or books, in my humble opinion. Here, we will attempt to give this trio its proper due and uncover its mysteries.

Undefined

This keyword is both a data type and value in JavaScript. It is one of six primitive data types, the others being: stringnumberbooleannull, and symbol (ES5+). It is assigned, by default, to any variable whose value has not yet been defined. On a deeper level, this means that the variable exists but its value has been given an empty value, called _undefined_. JavaScript is a dynamically typed language, which means that the JS engine determines the type of a variable based on the data type of the value assigned to it. In that context,undefined really means that JavaScript doesn’t know about type of the variable declared because it has yet to be initialized with a value.

Any unassigned variable is automatically given the value and type of undefined

We can illustrate this with the code below.

let myVar;  //declared but left unassigned
console.log(myVar)

Output: undefined

Undefined is also a data type, hence the following:

console.log(typeof myVar)

Output: "undefined"

Notice that there’s a slight difference between the value and the type of undefined; the latter is in quotes. One of the questions that you may find on an interview question is:

What is the value of **typeof typeof undefined**?

The answer is: string

This means that we can type the following:

console.log(typeof myvar + “ variable”)

Output: undefined variable

We can therefore say that in JavaScript, _the data type of the data type of _undefined_ is __string_!

For functions, if the returned value is left unassigned, it returns undefined. More importantly, a function will also return undefined if a value was not returned.

function f(){
   return;
}

console.log(f())

Output: undefined

#keywords #javascript #undefined #nan #null

The Non-Value Trio of JavaScript