JavaScript: Global By Default

September 1, 2008

Here's a very simple JavaScript function that prints the sum of its arguments:

function sum() {
  s = 0;
  for(i=0; i < arguments.length; i++) {
    s += arguments[i];
  }
  return s;
}
document.write('sum = '+sum(1, 2, 3));

Looks simple enough. Translated directly into non-idiomatic Ruby, that would be:

def sum(*args)
  s = 0
  i = 0
  while i < args.length
    s += args[i]
    i += 1
  end
  s
end

So let's say you now want your sum function to return the sum of the factorial of each number. No problem:

function sum() {
  s = 0;
  for(i=0; i < arguments.length; i++) {
    s += factorial(arguments[i]);
  }
  return s;
}
function factorial(n) {
  f = 1;
  for(i=1; i <= n; i++) {
    f *= i;
  }
  return f;
}
document.write('sum = '+sum(1, 2, 3));

Oops. That prints 1, but the answer we were looking for was 9. Hmmm, let's translate it to ruby and see what we get:

def sum(*args)
  s = 0
  i = 0
  while i < args.length
    s += factorial(args[i])
    i += 1
  end
  s
end
def factorial(n)
  s = 1
  i = 1
  while i <= n
    s = s * i
    i += 1
  end
  s
end
puts sum(1, 2, 3)

Ok, so Ruby gives us 9. So what's up? The truth is that is not a direct translation. Here's the correct translation:

def sum(*args)
  $s = 0
  $i = 0
  while $i < args.length
    $s += factorial(args[$i])
    $i += 1
  end
  $s
end
def factorial(n)
  $s = 1
  $i = 1
  while $i <= n
    $s = $s * $i
    $i += 1
  end
  $s
end
puts sum(1, 2, 3)

This gives us the same result as the flawed JavaScript, which is 1. As you can see, in both functions, the variables s and i are declared as global variables, which you can tell by the $ sigil. But in JavaScript, variables are global by default. That's right, the simple little innocuous-looking i=0 in our JavaScript for loop defines a global variable. Here is the corrected JavaScript version:

function sum() {
  var s = 0;
  for(var i=0; i < arguments.length; i++) {
    s += factorial(arguments[i]);
  }
  return s;
}
function factorial(n) {
  var f = 1;
  for(var i=1; i <= n; i++) {
    f *= i;
  }
  return f;
}
document.write('sum = '+sum(1, 2, 3));

The moral of the story is always prefix your variable declarations with var. If you are a web developer who writes JavaScript and this is news to you, stop what you are doing an read Douglas Crockford's JavaScript: The Good Parts.

Posted in Technology | Tags Javascript

Comments Comments Feed

1. Good post! I remember the day that I found this out the hard way (some 3 years ago, on my first project involving javascript). It was an unpleasant surprise, to say the least. ; )


# Posted By Ethan Vizitei on Saturday, September 6 2008 at 11:46 AM

2. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:18 PM

3. How to make money from the cheap shoes business?
Firstly, do some research about the cheap shoes business. There are a lot of kinds of cheap shoes,
Nike Air Max
,
Nike SB Shoes
,
Adidas Originals
,
Adidas Stan Smith
,etc.
Secondly, find a good partner who can wholesale the cheap shoes to you with very low price, so that you can make sure of your profit. There are a lot of wholesalers in the world, however, some of them will take your money and don’t send you anythings. I recommend a good wholesaler: www.online268.com
. From this site, you can buy cheap shoes from China with very low price and the quality of the product is excellent.
Thirdly, learn some marketing skills. If you need to make profit from any business, the knowledge and the skills of marketing effort is necessary. You need to the 4 P's of marketing diligently, the 4P are product, position, promotion and price.
Here is some information about www.online268.com.
The site www.online268.com is a famouse site in China which is target at shoes business. The company who runs the site has good relationship with the retailers of all countries in the world. The shop owners from other countries buy the cheap shoes from this site, and then sell them to all over the world.

# Posted By online268 on Wednesday, September 1 2010 at 4:46 PM

4.
Cheap nfl jerseys are your best choice, and retail nfl apparell and drop shipping are accepted as well. Grade cheap nfl sports jerseys,Competitive price and Best service, We do hope nfl jerseys usa to do long-term business with every clients and help you improvefootball jerseys more benefit from your market.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:29 PM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)