Web Design & Development Forum

Web Developers Zone
  • FB
  • TW
  • LND
  • G+

What is the difference between using var keyword or not using var during variable declaration

open
Public

I have declared javascript variables. I have checked by 2 ways. By giving var keyword and omitting the var keyword. I have not found any difference between these two.   So, using the var keyword is optional. what is the benefit here?
 

  1. I found the answer from one of my colleague. Thanks in advance to him. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables.

    Example:
    <script>
    var x = 5;
    function fnone() {
    var x = 6;
    alert("first : " + x);
    }

    function fntwo() {
    x = 7;
    alert("second: " + x);
    }

    alert(x); // Alerts 5
    fnone(); // Alerts 6
    alert(x); // Alerts 5
    fntwo(); // Alerts 7
    alert(x); // Alerts 7
    </script>
    After executing the function fnone, the value of x is still 5, but after the execution of fntwo function, the value of x has overwritten.

Please login or Register to Submit Answer