[ACCEPTED]-Why isn't it a must to declare a variable in Javascript before using it?-variables

Accepted answer
Score: 14

Javascript was intended for very simple 17 scripts in the browser. Requiring variable 16 declarations seemed unnecessary.

Of course, it's 15 an error in the language. And the makers 14 of javascript know that. They wanted to 13 change it. But they couldn't. Why?

Because 12 Microsoft had already reverse engineered 11 JavaScript and created their duplicate JScript, with 10 bugs and all. Microsoft vetoed any changes, even 9 bugfixes, since they were adamant about 8 not breaking anyones scripts. So even if 7 they changed JavaScript, JScript in IE would 6 stay the same.

It's not a good reason. But 5 it's the one we have.

Source: I got my javascript 4 history class from Douglas Crockford: "The 3 JavaScript Programming Language", http://video.yahoo.com/watch/111593/1710507 This 2 part of the story is between 9 and 11 minutes 1 into the video.

Score: 4

Good reasons? Honestly can't think of one, it's 11 one of the few things I really dislike about 10 JS.

It's possible because everything happens 9 within the global scope if not otherwise 8 controlled and JS allows implicit variable 7 creation like this. The cost of this is 6 enormous potential for scoping bugs and 5 pollution, and only benefit given that "this" exists 4 to explicitly define self scope and "window" and 3 "document" exist for global referencing, is 2 saving a few characters - which is no reason 1 at all.

Score: 1

My question is 'why it is allowed in javascript 10 to use a variable directly without declaring 9 it' as most of the programming languages 8 have a strict check on this.

That's the difference 7 between statically and dynamically typed 6 languages. Javascript is dynamically typed, so 5 there is no need to declare first. As it 4 was pointed out in other answers, var keyword 3 is more responsible for scope of a variable 2 than its declaration.

And I don't think that 1 most programming languages have a check on that.

Score: 1

Lua has a similar issue: any non-declared variable 7 is global by default. In the mailing list 6 it's a recurring theme, asking why shouldn't 5 it be 'local by default'. unfortunately, that 4 would introduce very nasty ambiguities in 3 the language, so the conclusion typically 2 is "global by default is bad, local 1 by default is worse"

Score: 0

Because it is a scripting language. Fact 1 kids. And that is how it was designed!

More Related questions