Wednesday, August 7, 2013

Variable scoping in python and javascript

As I was reviewing a colleague's code a few days ago, I ran across the following:

Having spent the last few weeks reading through Code Complete, defining the variables outside the loop stuck out to me as a problem - a case of pre-mature optimization.  I suggested the following:

Reducing the scope of the variable just felt cleaner, and the discussions I found here and here seemed to back this up.

But when this came up when talking with a friend later in the day, he mentioned that he didn't think javascript even maintained scope inside "for" loops.  Coming from C++, I thought loops in both javascript and python would hold scope.  The following were our test functions, entered on the Chrome Developer Tools command line for javascript and the REPL for Python.

The output from both these tests are the same: x is defined.  This is because both python and javascript lack block scope, something very much present in C++.

In the particular case I was discussing, the choice becomes a big more grey.  There are strong opinions on both sides of the fence.  At this point I agree with the accepted answer on the linked StackOverflow discussion: "For the case where a variable is used temporarily in a section of code, it's better to declare var in that section, so the section stands alone and can be copy-pasted."  I think the use "var" can be as helpful for people as compilers, and it makes the intent of a block of code more clear.  Using "var" on a variable in a code block says to me that this variable is intended for use in this code block, and may not have any meaning outside of it.