Type of Undeclared Variable in JavaScript: What is it?

Dhananjay Kumar / Friday, April 05, 2019

Have you ever thought, what is type of undeclared variable in JavaScript? I know, the first thing that might come to mind is: how can an undeclared variable have a type? Yes, in JavaScript it is possible.

To understand it, let us start with understanding types in JavaScript. There are seven built in types in JavaScript. They are as follows:

  1. null
  2. undefined
  3. boolean
  4. number
  5. string
  6. object
  7. symbol (added on ES6)

Each variable with assigned value has a type. Let us consider the code listed below:

var foo = 9;
console.log(typeof (foo)); // number
var koo;
console.log(typeof (koo)); // undefined
var too = 'Infragistics';
console.log(typeof (too)); // string

As you can see in the above snippet, if there is no value assigned then type of variable is undefined.  

So far so good, we saw that variable with no assigned value is undefined.  Let us consider the next code snippet:

var koo;
console.log(koo); // undefiend
console.log(typeof (koo)); // undefined

We have created a variable koo and have not assigned any value to it.  Now both value and type of koo are set to undefined.

Now that you understand type and value associated with undefined, let’s move on to null. In JavaScript, null is a primitive type.  However, type of null value is object. Consider code listed below:

var foo = null;
console.log(foo); // null
console.log(typeof (foo)); // object

You may consider it as a legacy bug that type of null value is object in JavaScript.

Finally, yet equally as important, in JavaScript a variable which is not declared also has a type. The declared variable type is undefined.

console.log(foo);// error foo is not defined
console.log(typeof (foo)); // undefined 

When you read the value of variable, which is  not declared, JavaScript will  return an error “not defined”, and will return its type as undefined

In addition, keep in mind that in world of JavaScript not defined is not the same as undefined.  I hope now you understand various primitive types in JavaScript.