I am new to JavaScript.
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.
That second var x is totally superfluous.
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>
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.
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);
Within the same scope, it is totally unnecessary to "redeclare" a variable.