What happens if we re-declare a variable in JavaScript?

When you re-declare a variable in JavaScript using var, the original value is preserved. The re-declaration doesn't reset or change the variable's value.

Example

Let's see an example where we declare the variable age twice:

<html>
   <head>
      <title>Variable Re-declaration Example</title>
   </head>
   <body>
      <script>
         var age = 20;
         var age;  // Re-declaration without assignment
         
         if (age > 18) {
            document.write("Qualifies for driving");
         }
         
         document.write("<br>Age value: " + age);
      </script>
   </body>
</html>
Qualifies for driving
Age value: 20

What Happens During Re-declaration

When you re-declare a variable with var, JavaScript treats it as if you just mentioned the variable name again. The declaration is ignored, and the value remains unchanged.

var name = "John";
console.log("Before re-declaration:", name);

var name;  // Re-declaration
console.log("After re-declaration:", name);

var name = "Alice";  // Re-declaration with new value
console.log("After assignment:", name);
Before re-declaration: John
After re-declaration: John
After assignment: Alice

Behavior with let and const

Unlike var, re-declaring variables with let or const in the same scope throws an error:

let count = 5;
let count = 10;  // SyntaxError: Identifier 'count' has already been declared

const PI = 3.14;
const PI = 3.14159;  // SyntaxError: Identifier 'PI' has already been declared

Key Points

  • var allows re-declaration without errors
  • Re-declaring with var preserves the original value
  • let and const prevent re-declaration in the same scope
  • Assignment during re-declaration updates the value

Conclusion

Re-declaring a var variable in JavaScript doesn't change its value unless you also assign a new value. Modern JavaScript prefers let and const which prevent accidental re-declarations.

Updated on: 2026-03-15T21:27:35+05:30

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements