Broken javascript word counting code that irritates me

Based on the Javascript: The Good Parts by Douglas Crockford.
(I highly recommend this book to everyone.)

<script type='text/javascript'>
var s = "Constructor is a Constructor";
var word_cnt = {};
var words = s.toLowerCase().split(/ /);
var i;
for (i = 0; i < words.length; i++) {
  if (word_cnt[words[i]]) {
    word_cnt[words[i]] += 1;
  } else {
    word_cnt[words[i]] = 1;
  }
}

for (w in word_cnt) {
  document.write(w + ": " + word_cnt[w] + "<br>");
}
</script>

Output:
constructor: function Object() { [native code] }11
is: 1
a: 1

Reason:
Because you have ‘Constructor’ in your parent class (or prototype) of word_cnt!!!!!!
And that’s a string! So you add 1 to that string! and 1 is coerced to a string, thus the result is a string!
Sigh… Given that javascript is now really the future, this makes me want to cry.

Similar Posts:

Comments 2