JavaScript variable initialization

1 min


Initialization is a very important task in all programming languages. Not initializing any variable with proper type is the root cause of many many IT application problems.

This article is an experiment in JavaScript variables.

JavaScript dynamically assigns datatypes. The type of value you assign, the variable becomes of that same type. But before you assign any value, what exactly it contains?

Lets declare a variable and see it contents.



If you run the above script, you would see an empty alert box. So what “i” contains? Nothing? Not really. Lets modify the above example with below:



Now, if you run the script, this time you would see alert box with message undefined. So what happened? Well, when you just declare a variable and did not assigned anything to it, it holds ‘undefined’. Now its not a string. Its like variable i doesn’t have anything.

So how do we know if a variable holds undefined? Or, rather, it is not yet assigned any value. Well, you can directly check with the ‘undefined’ constant. So, in this below example, if run, it would show the alert box with “I’m inside IF”.



So what would happen – if we assign an empty string to the variable i? Consider below example. If run, it would alert the message mentioned inside ELSE statement. Because, as soon as i is assigned to a string, it became a string type variable.



Lets make this more complicated by removing undefined and putting a zero as below. What do you think would be the output? Well, surprise! It would execute the statement inside IF.



So, JavaScript dynamically assign types of the variables based on what you assign to it.



Have any thoughts? Drop a comment.


Arindam

Creator and author of debugpoint.com. Connect with me via Telegram, 𝕏 (Twitter), or send us an email.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments