7 Common Javascript Mistakes or Confusions

While helping folks with Javascript on Stackoverflow or IRC, I've noticed some common mistakes or confusions. I've made a list of these in my little notebook and have been covering each of them in a different blog post over the last month or so. This post wraps up this series: and the 7 common Javascript mistakes or confusions are:

  1. Not using var to declare your variables. This will work but will make your variables global, which will likely become a source of strange errors later down the road. Always use var.

  2. Calling your callbacks before you mean to. certain browser API's or libraries expect functions as arguments, don't prematurely call the function before passing it in.

  3. Expecting this to be something else. Often when you create a callback function within another function, the value that's bound to this - or the context - changes. Understanding how context is bound is helpful here, and often, the simplest fix is to save this into a variable just outside the callback.

  4. Incorrectly making callback functions in loops. Creating callback functions - such as event handlers inside of a loop can get tricky - it may not do what you'd expect if it depends on the loop counter. The solution is to introduce yet another function to act as a closure.

  5. Processing intensive tasks without locking up the browser. Sooner or later in a Javascripter's life, you will encounter a case when you need to process a lot of data, and the processing takes so long that the entire browser becomes unresponsive. But, in Javascript you can't simply use a sleep(1) like some other languages to yield execution in the loop. The solution is a mix of task queuing and async programming using setTimeout.

  6. Coping with life without a compiler. Programmers coming from a background of a compiled programming language will often find it frustrating that there isn't a compiler to catch errors for you in Javascript. The solution is to use the interactive console to aid your development process - I also made an 8-minute screencast on using the console.

  7. Grokking OOP in Javascript. Object-oriented programming in Javascript is very different from pretty much any mainstream programming language, and is a big source of confusion for new Javascripters. No worries, this crash course on Javascript object inheritance will guide you through it, starting with first principles.

Happy coding!

Ever feel like you are wasting your life away debugging?
It doesn't have to be this way. Check out my debugging course.
blog comments powered by Disqus