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.
alertdoesn’t work because, in the case ofb, it doesn’t exist in the correct scope and in the case ofait hasn’t been instantiated yet because you haven’t called the functiontestvarcreates a variable which is local to the scope in which it is called. Without var you create a global variable.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 throughvarand a tool like jsLint you won’t run into the problem of a misspelling in a variable name throwing your code out of wack.