6 secrets of JavaScript Jedis

Are you a competent JavaScript developer but have yet to hit Jedi-level secrets? No worries -- these steps will take you to the next level

Page 2 of 3

JavaScript secret No. 2: Higher-order functions

In functional programming languages, functions are first-class members. They can be passed around like any other value, which opens up interesting possibilities.

Higher-order functions refer to those that consume or produce other functions. Methods on the function prototype, such as call and bind, are both higher-order functions. Techniques such as currying and memoization can both be expressed as higher-order functions. Aspect-oriented programming can also be achieved in JavaScript using higher-order functions.

JavaScript secret No. 3: Invoking functions

After understanding the most common way to invoke a function (using the parentheses operator), it's time to learn how to use call and apply. The benefit of using call/apply over the parentheses operator is that you can specify the context in which the function will execute (the value of this). You'll see this often in higher-order functions, particularly when they consume functions to execute later. The internals of the bind method of the Function prototype is a great example of call/apply.

// Possible implementation of bind using apply

function bind(func, context){

return function(){

func.apply(context, Array.prototype.slice.apply(arguments));



JavaScript secret No. 4: What's this?

The this keyword is a huge stumbling block for many JavaScript developers to the point that some avoid it altogether. The best description of the topic I've seen so far was by Yehuda Katz in his blog post on function invocation. When not using call/apply or bind, the this value will always refer to the global object, except in the following instances:

  1. The function in question was called with the new operator, in which case this points to a new object being constructed.
  2. The function in question is a member of an object, in which case this points to the object.

Rule 2 should be disregarded whenever the function involved is being called asynchronously, such as in a click handler or setTimeout. For example:

Person.getName(); // 'this' points to Person

setTimeout(Person.getName, 1000); // 'this' points to the global object

| 1 2 3 Page 2