Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any purpose to redeclaring JavaScript variables?

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.

like image 591
Warrior Avatar asked Dec 08 '09 01:12

Warrior


1 Answers

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);
like image 153
Christian C. Salvadó Avatar answered Oct 04 '22 03:10

Christian C. Salvadó