Type of Undeclared Variable in JavaScript: What is it?

 

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

view raw

typeofjs1.js

hosted with ❤ by GitHub

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

view raw

typeofjs2.js

hosted with ❤ by GitHub

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.

Read full article on the Infragistics blog


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading