6

I am new to JavaScript.

<html>
<body>
<script type="text/javascript">
var x=5;
document.write(x);
document.write("<br />");
var x;
document.write(x);
</script>
</body>
</html>

Result is:

5
5

When x is declared the second time it should be undefined, but it keeps the previous value. Please explain whether this redeclaration has any special purpose.

Boann
  • 48,794
  • 16
  • 117
  • 146
Warrior
  • 39,156
  • 44
  • 139
  • 214
  • The content of your question is about one specific example, which has been answered well enough below. However, I found that [this answer](http://stackoverflow.com/a/12889928/983430) to a similar question answers the generic case (when/why would redeclaring a JavaScript variable be used?) asked in the title of your question really well. – Amos M. Carpenter Oct 31 '12 at 09:05

9 Answers9

21

You aren't really re-declaring the variable.

The variable statement in JavaScript, is subject to hoisting, that means that they are evaluated at parse-time and later in runtime the assignments are made.

Your code at the end of the parse phase, before the execution looks something like this:

var x;
x = 5;

document.write(x);
document.write("<br />");
document.write(x);
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
7

var alone does not perform an assignment. It only flags that when you use the variable name throughout the scope in which the var occurs, you are talking about a local variable and not global (the controversial default). The var is spotted when the function is parsed and holds throughout that scope, so where you put it is irrelevant:

var a= 0;

function foo() {
    a= 1;
    return a;
    var a;
}

var b= foo();
alert('global a='+a+', local a='+b);

Results in global a= 0, local a= 1: even though the var statement is never reached in the course of execution of foo(), it is still effective in making a a local variable.

So declaring var x a second time in the same scope is completely redundant. However you might sometimes still do it, typically when you re-use a local variable name for a second independent use within the same function. Most commonly:

for (var i= 0; i<onething.length; i++) {
    ...do some trivial loop...
}

for (var i= 0; i<anotherthing.length; i++) {
    ...do another trivial loop...
}

Whilst you could certainly omit the second var, and tools like jslint would demand you do so, it might not actually be a good idea.

Imagine you later change or remove the first loop so that it no longer declares i to be var. Now the remaining second loop suddenly changes meaning from a local to a global variable. If you fail to notice when updating the first loop that the second loop has a hidden dependency on it (and you might very well fail to notice that given how the eyes elide the pattern for(...=0 ; ...<...; ...++) into “oh, that's just a standard iterator”), you've got a subtle and annoying-to-debug problem.

bobince
  • 528,062
  • 107
  • 651
  • 834
1

As far as my understanding of javascript goes, the use of the var keyword is completely optional in the global scope. It's a different story for functions.

When inside a function, use the var keyword to indicate that the variable is local to the function (as opposed to being global by default).

I personally use var in the global scope to show that a variable is being declared and/or utilized for the first time.

You can reference http://www.w3schools.com/js/js_variables.asp for more info.

Kenaniah
  • 5,171
  • 24
  • 27
  • 2
    no it is not: without specifying `var`, a variable would fall in the global scope. – jldupont Dec 08 '09 at 01:33
  • var is used for scope within a function, inside a function if you dont use var it is automatically global. – John Boker Dec 08 '09 at 01:33
  • heh - all within the same 20 seconds. – John Boker Dec 08 '09 at 01:34
  • @Kenaniah: you should delete your answer or you risk having a bunch of down-vote really soon... – jldupont Dec 08 '09 at 01:38
  • My apologies. I forgot to mention it's usage within functions to indicate a local variable (versus global). Although the question pertains to the global scope, I should have included that. Post edited ;-) – Kenaniah Dec 08 '09 at 01:39
1

so when the second time when its declared x should be undefined

What part of the specification says this?

"Undefined behaviour" does not mean "the variable will be undefined".

Anon.
  • 58,739
  • 8
  • 81
  • 86
0

That second var x is totally superfluous.

Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
0

Within the same scope, it is totally unnecessary to "redeclare" a variable.

jldupont
  • 93,734
  • 56
  • 203
  • 318
0

Also, a programmer might want to use var to localize a variable:

<script>
var x= 'this is global x';
function my_x() {
 var x= 'localized x';
 alert(x);
}
my_x();
alert(x);
</script>
leepowers
  • 37,828
  • 23
  • 98
  • 129
  • Although this is possible and a very good description of it, I'm not sure that this is a very good practice to get into, variable names shouldn't generally be repeated with different uses. – Jay Dec 08 '09 at 01:46
0

You should never redeclare a variable within the same scope, if you really want to change this then assign to it. Redeclaration is not required to create a different object in this dynamic language, if you want x to be a string just assign:

x = "hello";

It is not required that you set it back to undefined or redeclare first.

Please note that changing the variable type is not very good practice in most situations, simply stating that it is a possibility if that's what you require.

Jay
  • 4,240
  • 3
  • 26
  • 39
0

I recently wrote code like:

var obj1 = get_an_object();
var v = obj1.get_velocity();
v += changes_in_velocity();
obj1.set_velocity(v);

var obj2 = get_an_object();
var v = obj2.get_velocity();
v += changes_in_velocity();
obj2.set_velocity(v);

(The actual code was more complicated and less repetitive)

So far as the browser is concerned, the second var v statement was redundant and pointless. To me, it served two purposes. It said to forget everything I knew about the old v, because this was a new usage. And it meant I could re-order the code, or comment out the first half, without breaking things.

dspeyer
  • 2,904
  • 1
  • 18
  • 24