Can re-declaring a variable destroy the value of that variable in JavaScript?

Re-declaring a variable will not destroy the value of that variable, until and unless it is assigned with some other new value.

If we look at the following example variables "x" and "y" were assigned with values 4 and 8 respectively, later on when those variables were reassigned, the old values were replaced with the new values and displayed as shown in the output.

Example: Re-declaring with New Values

<html>
<body>
    <script>
        var x = new Number(4);
        var x = 7;
        var y = 8;
        var y = 10;
        document.write(x);
        document.write("<br>");
        document.write(y);
    </script>
</body>
</html>
7
10

Example: Re-declaring Without Assignment

In the following example, the variables were re-declared, but their values were not reassigned. Therefore those variables retained their original values.

<html>
<body>
    <script>
        var x = new Number(4);
        var x;
        var y = 8;
        var y;
        document.write(x);
        document.write("<br>");
        document.write(y);
    </script>
</body>
</html>
4
8

How It Works

When you re-declare a variable using var keyword:

  • Without assignment: The variable keeps its current value
  • With assignment: The variable gets the new assigned value
  • JavaScript ignores duplicate var declarations for the same variable name

Modern Approach with let and const

Unlike var, let and const don't allow re-declaration in the same scope:

<html>
<body>
    <script>
        let x = 5;
        // let x = 10; // This would cause an error
        x = 10; // This is reassignment, not re-declaration
        document.write(x);
    </script>
</body>
</html>
10

Conclusion

Re-declaring a var variable without assignment preserves its value. Only reassignment changes the value. Modern JavaScript prefers let and const which prevent accidental re-declarations.

Updated on: 2026-03-15T23:18:59+05:30

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements