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.


We bring the latest tech, software news and stuff that matters. Stay in touch via Telegram, Twitter, YouTube, and Facebook and never miss an update!

Join our Telegram channel and stay informed on the move.

Also Read

SEE ALSO:   How to Play or Capture video in HTML5 Canvas

Like it? Share with your friends!

Arindam

Creator of debugpoint.com. All time Linux user and open-source supporter. Connect with me via Telegram, Twitter, LinkedIn, 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
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x