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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: