HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Introduction to arrow functions in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptfunctionsarrowintroduction

Problem

In order to understand arrow function syntax, we should start by refactoring a regular function step by step:
We can start by refactoring the function declaration to use a variable assignment:
Then, we can refactor the regular function to an arrow function:
If there's only one argument, we can omit the parentheses around it:
If the function is a single expression, you can omit the curly braces and return statement and use an implicit return:

Solution

function square(a) {
  return a * a;
}


Then, we can refactor the regular function to an arrow function:
If there's only one argument, we can omit the parentheses around it:
If the function is a single expression, you can omit the curly braces and return statement and use an implicit return:
The main difference between arrow functions and regular functions is execution context (i.e. the value of this). Technically speaking, most other differences often mentioned either stem from this one or are side effects of it.
In a regular function, this is dynamic and depends on how the function was invoked:
Arrow functions, unlike regular ones, don't define their own execution context therefore this inside an arrow function always refers to the lexical this (i.e. the scope in which the arrow function was defined).

Code Snippets

function square(a) {
  return a * a;
}
const square = function (a) {
  return a * a;
}
const square = (a) => {
  return a * a;
}

Context

From 30-seconds-of-code: arrow-functions

Revisions (0)

No revisions yet.