When I was at a coding boot camp learning about JavaScript and ES6, everyone in class seemed to have some level of confusion around normal function declarations and the new ES6 arrow function declarations. Common questions we had included:

  • When should we use normal functions or arrow functions?
  • What are the differences between normal functions and arrow functions?
  • Are we able to use one or the other in all situations for consistency?

After doing some research, I found that normal functions and arrow functions are actually not interchangeable in certain circumstances. Apart from the syntax, normal functions and arrow functions have another major difference: the way they bind the this keyword in JavaScript.

Let’s look at a very simple example. Suppose we have a simple JavaScript object:

const obj1 = {
	  fullName: 'Object 1',
	  color: 'red',
	  print: function() {
	    console.log(`${this.fullName} is ${this.color}`);
	  }
	};

	obj1.print(); // Object 1 is red
view raw
object1.js hosted with ❤ by GitHub

We have a print method on obj1 that logs a string to the console. The result is what we have expected, that this in the print method refers to obj1 itself.

Now let’s create another object with a slightly different print method:

const obj2 = {
	  fullName: 'Object 2',
	  color: 'blue',
	  print: function() {
	    setTimeout(function() {
	      console.log(`${this.fullName} is ${this.color}`);
	    }, 1000);
	  }
	};

	obj2.print(); // undefined is undefined
view raw
object2.js hosted with ❤ by GitHub

Now the print method will only log the resulting string after one second due to setTimeout . But why is it logging undefined is undefined instead of Object 2 is blue ?

#es2015 #javascript #es6 #javascript-tips #arrow-functions #function

JavaScript: The Good Parts of Arrow Functions
2.05 GEEK