|
In this article I will explain importance of var in Javascript Step 1: Create an aspx page with a button control. Button will invoke fnCall javascript
<asp:Button ID="btnTest" Text="Test Javascript" OnClientClick="return fnCall();" runat="server" />
Step 2: Add below javascript on the same page < script language="javascript" type="text/javascript">
function fnCall() { for (x = 0; x < 10; x++) { fnCall1(); alert(x); } return false; } function fnCall1() { for (x = 0; x < 10; x++) { //your code } } </ script>
Step 3: Now run the page and click on Button, you will notice that alert is coming only once with value 10 insted of 10 alerts with 1 to 10. Actually this behavious is quite obvious because x is global. If the variable doesn’t have var, javascript treats it as a global variable. Since the x doesn’t have var, javascript treats it as a global variable. When fnCall1 is called, loop increments the value of x to 10 making fnCall to run only once.
To resolve the issue, declare x with var
<script language="javascript" type="text/javascript">
function fnCall() { for (var x = 0; x < 10; x++) { fnCall1(); alert(x); } return false; }function fnCall1() { for (x = 0; x < 10; x++) { //your code } } </ script>
|