In Javascript we don't have to declare a variable with var
keyword before using it. We can straight away do things like myCount = 12;
or myStr = "Hello";
(where myCount, myStr are not declared before). Any such usage, declares and initializes the variables in the 'global' scope.
What could be the reasons for providing this feature? And is it a good standard at all?
UPDATE: My question is not what the differences are between 'using a variable without declaring' and 'declaring and then using' and how it affects scope.
My question is 'why it is allowed in javascript to use a variable directly without declaring it' as most of the programming languages have a strict check on this.
UPDATE : I see the following quoted text as a bad effect of this feature. So, why have this feature at all?
"Suppose there is a globally declared variable x
(var x="comparison string"
) already which i am unaware of and i with intention of creating my own global 'x' inside one of my functions initialize one(x=-1
) and there i end up breaking other functionality.
So, is there any good reason at all? for having this feature?
Javascript was intended for very simple scripts in the browser. Requiring variable declarations seemed unnecessary.
Of course, it's an error in the language. And the makers of javascript know that. They wanted to change it. But they couldn't. Why?
Because Microsoft had already reverse engineered JavaScript and created their duplicate JScript, with bugs and all. Microsoft vetoed any changes, even bugfixes, since they were adamant about not breaking anyones scripts. So even if they changed JavaScript, JScript in IE would stay the same.
It's not a good reason. But it's the one we have.
Source: I got my javascript history class from Douglas Crockford: "The JavaScript Programming Language", http://video.yahoo.com/watch/111593/1710507 This part of the story is between 9 and 11 minutes into the video.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With