Door 01 | JS Adventskalender
Skip to content

Door 01

Published: at 07:00 AMSuggest Changes

Arrow Functions – Elegant Syntax for Functions

Since the introduction of ES6 (ECMAScript 2015), JavaScript has received many useful features that make writing clean and efficient code easier. One of these features is Arrow Functions, which provide a compact and readable syntax for functions.

What are Arrow Functions?

Arrow Functions are a new way of writing functions. They use a shorter syntax than traditional function expressions and bind the this keyword lexically, avoiding some of the typical pitfalls when dealing with this.

Syntax of Arrow Functions

The basic syntax of an Arrow Function looks like this:

// Traditional function
function add(a, b) {
  return a + b;
}

// Arrow Function
const add = (a, b) => {
  return a + b;
};

For even more brevity, you can simplify the function body with Arrow Functions:

Lexical this Binding

A significant advantage of Arrow Functions is the lexical binding of this. In traditional functions, the value of this can vary depending on the calling context. Arrow Functions, on the other hand, inherit the value of this from the surrounding context.

Example with traditional function (incorrect):

function Person() {
  this.age = 0;

  setInterval(function() {
    this.age++;
    console.log(this.age);
  }, 1000);
}

const p = new Person();
// Output: NaN, because 'this' inside the function does not refer to the 'Person' object

Example with traditional function (correct):

function Person() {
  // sets "this" to a helper value "that" so it is known in the "setInterval" method.
  const that = this;

  this.age = 0;

  setInterval(function() {
    // Uses "that" instead of "this", which is reset here.
    that.age++;
    console.log(that.age);
  }, 1000);
}

const p = new Person();
// Output: 1, 2, 3, 4, 5, ... increments age by 1 every second and outputs it.

Solution with Arrow Function:

function Person() {
  this.age = 0;

  setInterval(() => {
    // Uses "this" because its context is not reset.
    this.age++;
    console.log(this.age);
  }, 1000);
}

const p = new Person();
// Output: 1, 2, 3, ..., because 'this' correctly refers to the 'Person' object

Practical Use Cases

Important Notes

Conclusion

Arrow Functions are a powerful tool for making JavaScript code more compact and readable. They are excellent for short functions and callbacks, especially when you want to use lexical this binding. However, they should be used judiciously, as they are not the best choice in all situations.

Experiment with Arrow Functions and discover how they can improve your code!


Previous Post
Door 02