Skip to main content
2 of 6
added 809 characters in body
sunwukung
  • 2.3k
  • 1
  • 17
  • 29

Javascript is prototypal first, with functional capabilities. The important thing to bear in mind (IMO) is that while JS can utilise some functional patterns, it is not always well equipped to execute then.

Take iterating over an array, for example. You can do this using a functional style or the native loop constructs - and generally speaking the loop is more performant. Take this example - hit it with loops of increasing size and record the execution times in different browsers (i've done this already, but I've lost the benchmarks - sorry!):

var test = ['foo', 'bar', 'baz'], removeFunc, removeLoop;

//(semi)functional style...
removeFunc = function(src, trg) {
    return src.length === 0 ? 
        src : 
            src[0] === trg ? 
                src.slice(1) : 
                    [src[0]].concat(removeFunc(src.slice(1), trg));
};

//but this is faster
removeLoop = function(src, trg){
    var len = src.length, i=0, result = [];        
    while(i < n){
       if(src[i] !== trg){
          result.push(src[i]);
       }
       i = i+1;
    }
}

In addition, if you use a functional construct to hit loops of considerable size and don't utilise some form of ad-hoc stack management you could flood the stack (although, to be fair, you need a BIG list for this to occur...). You've also got to factor in to the mix the variant optimisations in each browser - although if you're working in a Node.js environment this is obviously more of a fixed target.

That's not to say you shouldn't use functional constructs in Javascript - just be aware of the limitations in it's implementation relative to it's environment.

sunwukung
  • 2.3k
  • 1
  • 17
  • 29