0

I'm wondering why we write this:

for (var i=0; i<11 ; i++){
  console.log("The number is "+i)
}

Instead of just this:

for (i=0; i<11 ; i++){
  console.log("The number is "+i)
}

Is the "var i" necessary? If not, why do we put it? Both code blocks return the same thing and work.

coder02033
  • 43
  • 5
  • *"Is the "var i" necessary?"* Yes. Without it, your code is falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) -- it's creating a **global** variable called `i`. This was arguably a mistake in the definition of JavaScript; one that's been corrected by strict mode, where assigning to an undeclared variable is the error it always should have been. – T.J. Crowder May 22 '20 at 12:49
  • Not a very good duplicate. See e.g. https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it – Guy Incognito May 22 '20 at 12:49
  • I misunderstood your comment. – coder02033 May 22 '20 at 14:24

0 Answers0