Arrow Functions in JavaScript

DZone 's Guide to

Arrow Functions in JavaScript

Arrow functions are a new and powerful part of ES6 JavaScript. In this tutorial, we take a look at how to use them properly.

· Web Dev Zone ·
Free Resource

Arrow functions are the most powerful feature in ES6, especially in TypeScript. Let's look at one simple example of this using a forEach loop.

//Normal Statement with a callback function
arrayOfItems.forEach(function(x) {

//arrow function
arrayOfItems.forEach((x) => {

In a JavaScript class, we use this keyword to refer to the instance of the class .But here are some cases likemyObject.myMethod1() here this used inside my first method, which will refer to myObject. Another example you can with this snippet.

var log = console.log;

This will generate an error because the log expects this to refer to the console, but the console within that reference was lost. We can fix this is by using bind() method.

var log = console.log.bind(console);

Another instance where this is confusing is with respect to anonymous functions:

class getDateFromServer(){
init() {}
getDataById()(function callback(err,data) {
this.init(); // this will not work

In strict mode, it will be undefined. So arrow functions don’t set a local copy of this.

class Javascript {
  constructor(frameworks) {
    this.frameworks = Array.isArray(frameworks) ? frameworks : [];
  outputList() {
      .forEach((f, i) => console
        .log(f, i + '-' + this.frameworks.length)  // `this` works! 

var ctrl = new Javascript(['Angular', 'React']);


anonymous functions ,arrow functions ,javascript tutorials ,web dev

Published at DZone with permission of Puneet Sharma , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}