Search code examples
javascriptvariablesredeclaration

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.


Solution

  • 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);