HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Arrow Functions

Arrow functions were introduced in ES6. They allow us to write shorter function syntax and solve one of the most frustrating problems in JavaScript: the behavior of the this keyword.


The Shorter Syntax

An arrow function uses the => (fat arrow) operator.

// Traditional
const x = function(x, y) {
   return x * y;
}

// Arrow
const y = (x, y) => x * y;

Implicit Returns

If the function has only one statement, and that statement returns a value, you can remove the brackets {} and the return keyword.

// Shortest version
const hello = () => "Hello World!";

Parameter Shortcuts

If there is only one parameter, you can omit the parentheses as well.

// One parameter
const greet = name => "Hello " + name;

The 'this' keyword in Arrow Functions

In regular functions, the this keyword represented the object that called the function, which could change depending on the context. In arrow functions, there is no binding of this.

Instead, this inside an arrow function refers to the parent scope (lexical scoping) at the time it was defined. This makes arrow functions perfect for things like setTimeout or event listeners where this usually gets lost.

Warning: Arrow functions are not suited for object methods because they won't point to the object itself.
const person = {
  name: "Mim",
  // BAD: sayHi will point to the Window object, not person
  sayHi: () => {
    console.log("Hi " + this.name); 
  }
}

Key Points to Remember

  • => is used to define arrow functions
  • They offer a shorter, cleaner syntax for small logic blocks
  • Single statement functions have an implicit return
  • Arrow functions inherit this from their surrounding context (lexical this)
  • They are not hoisted—you must define them before calling them
  • They cannot be used as constructors (you cannot use new with an arrow function)