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:
- null
- undefined
- boolean
- number
- string
- object
- symbol (added on ES6)
Each variable with assigned value has a type. Let us consider the code listed below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
Leave a Reply