Reputation: 575
I want to know what's the difference when declare a variable whether using var
. i used the following code:
<body>
<h1>New Web Project Page</h1>
<script type="text/javascript">
function test(){
a = "hello";
var b="world";
}
alert(a);
alert(b);
</script>
</body>
Why the alert doesn't work and what's the difference when declare a variable whether using var
in javascript.
Upvotes: 0
Views: 5718
Reputation: 9823
Exact same question regarding use of 'var' has been answered here
Regarding why your alert doesn't work, it is because you haven't called the 'test()' function. It has just been created...it will do nothing. You'll need to call it in order to populate the variables.
Upvotes: 1
Reputation: 35309
Declaring a variable without var
makes it global so anything can access it. The reason your alert doesn't work however is due to you never calling test()
so a
or b
are never assigned. If you do call test
(before the alerts), b
will be undefined, and a
should read hello.
A great resource on variables and scoping.
Upvotes: 2
Reputation:
You're not invoking the test()
function. When the var
is excluded, variables become global, so they're available to all code.
Upvotes: 1
Reputation: 32484
alert
doesn't work because, in the case of b
, it doesn't exist in the correct scope and in the case of a
it hasn't been instantiated yet because you haven't called the function test
var
creates a variable which is local to the scope in which it is called. Without var you create a global variable.
function fn ( ) {
var x = 0; // this variable is local to the function fn
y = 10; // this variable is global and can be accessed
// from anywhere after you call fn
}
generally speaking, unless there is a good reason you don't want to use global variables. That is to say, you want to create all of your variables using var
. Putting variables only in the scope they are needed makes for easier to understand and maintain code. It also helps to alleviate the "Magic Variable" problem. Where you have variables that just appear but you don't have a clear idea of from where. It also makes it easier to debug your code because, in javascript, variables that don't exist get created on the fly. But if you only use local variables through var
and a tool like jsLint you won't run into the problem of a misspelling in a variable name throwing your code out of wack.
Upvotes: 4