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


Re-declaring a variable will not destroy the value of a 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

Live Demo

<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>

Output

7
10

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

Example

Live Demo

<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>

Output

4
8

Updated on: 29-Jun-2020

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements