0

in javascript atleast declaration is must before usage of variable but in the following code the variable i in the for loop is used without declaration and the code is working fine..... why???

 <body>
    <form>
    <input type="button" onclick="multi(a)" value="click here" > 
    </form>


    <script type="text/javascript" language="javascript">
    <!--
            var a;
            function multi(a){
            a=parseInt(prompt("Enter a value","your value goes here"));
                for(i=1;i<=10;i++){
                document.write(a+"X"+i+"="+a*i+"<br />");
            }
    }
    -->
    </script>
  </body>
rehman
  • 1
  • 2
  • the `i` inside a `for` loop is a little unusual because normally it's only used inside the loop. In other situations you'll want to declare and use variables based on normal scope rules. – Toby Jul 24 '16 at 15:31
  • 1
    It **should** have used `var` to declare `i`. @Toby no, that `i` in the code as written is a global variable. – Pointy Jul 24 '16 at 15:31
  • 1
    Or `let` depending on how old the browsers you want to support are. – Quentin Jul 24 '16 at 15:31

1 Answers1

1

When you haven't engaged strict mode, you can declare a variable (as a global) by assigning a value to it. It is only reading an undeclared variable that throws a ReferenceError.

This isn't considered good practise though, which is why it is banned in strict mode.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335