Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Never use anonymous functions in JS
2 points by z3t4 on Dec 14, 2014 | hide | past | favorite | 2 comments
I think I've found the silver bullet for the evil stuff in JS: Never use anonymous functions! You then no longer have to make closures or visit callback hell. And your code get easier to understand.


Lets say you have a bunch of textures and want to create a pattern for each of them. Most people would do it like this:

  for(var i=0; i < texcture.length; i++) {
    texcture[i].onload = function(i) {
      pattern[i] = ctx.createPattern(texcture[i], 'repeat');
    }
  }

Witch will summon the evil closure:

  for(var i=0; i < texcture.length; i++) {
    texcture[i].onload = (function(index) {
      return function() {
        pattern[index] = ctx.createPattern(texcture[index], 'repeat');
      };
    }
  })(i);

But if you used my silver bullet: Avoid anonymous functions - the root of evil ...

  for(var i=0; i < texcture.length; i++) {
    createPattern(i);
  }

  function createPattern(i) {
    texcture[i].onload = function() {
      pattern[i] = ctx.createPattern(texcture[i], 'repeat');
    }
  }


I don't understand the problem you think anonymous functions are causing, or how your solution of just not using them helps.

Sure, if you're littering your code with anonymous functions at the top level, you have no idea what is executing when or why. But who does that?

How do you think naming a function, then calling it is any better, if you just littered your function calls all over the place (assuming that is why you think this is a problem of course).




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: