Broken javascript word counting code that irritates me

Tags:

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.

Comments

2 responses to “Broken javascript word counting code that irritates me”

  1. JM Avatar

    자바스크립트를 앞으로 멀리하고 살겠다는 다짐을 다시 한번 되새겨 봅니다.

  2. mkseo Avatar
    mkseo

    하하 그러게요.

    다행인 것은 다음나오는 ECMA script 5 표준이 정해질때 새로운 기능을 추가하려는 안(script 5안)과 현재 언어의 문제점을 개선하려는 안(script 4.5안)이 경쟁하다가 결국은 4.5가 5로 올라가고 새로운 기능을 추가하는 안은 채택되지 않았다고 합니다.

    바라건데 새로 나올 버젼에서는 이런 말도 안되는 설계상의 문제는 좀 수정되지 않을까하고 생각하고 있습니다. 문제는 이경우 하위 호환성을 어떻게 유지할 것인가인데, 모르죠 그건;;;

    한가지 깨달은건 배우지 않고도 많이 쓰려고 드는 언어가 자바스크립트이지만, 배우지 않으면 제대로 쓸 수 없는 언어가 자바스크립트이란것이고, 자바스크립트 닌자들이 좋은 대우를 받는게 다 이유가 있단 겁니다.

    앞으로 이 언어가 얼마나 많은 사람을 울릴지 알 수 없는 일이네요 ㅎㅎ

Leave a Reply

Your email address will not be published. Required fields are marked *