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.
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.
Have any thoughts? Drop a comment.