惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Getting Started with Arrow Functions in JavaScript
Dmitri Pavlutin · 2020-09-08 · via Dmitri Pavlutin Blog

ES2015 had introduced a new way to define functions in JavaScript: the arrow functions. They have a concise syntax, can be inlined, fit great as callbacks, and resolve this lexically.

I'm going to explain in a few easy steps how to use arrow functions in JavaScript.

Table of Contents

  • 1. The syntax
  • 2. this value
  • 3. arguments object
  • 4. Shortening
    • 4.1 Omitting parenthesis
    • 4.2 Omitting curly braces
  • 5. Dos and don'ts
    • 5.1 Can be asynchronous
    • 5.2 Cannot be a method
    • 5.3 Cannot be a constructor
    • 5.4 Cannot be a generator function
  • 6. Summary

1. The syntax

The central symbol of an arrow function is the fat arrow =>. That's where the name arrow function came from.

Let's define an arrow function to greet a person:


const greet = (who) => {

return `Hello, ${who}!`;

};

greet('Eric Cartman'); // => 'Hello, Eric Cartman!'


greet is an arrow function. The symbol => delimits the parameters (who) and the function body { return `Hello, ${who}!` }.

greet('Eric Cartman') is how you call an arrow function. There's no difference between calling a regular function and an arrow function.

Generally, the syntax of the arrow function is this:


(param1, param2, ..., paramN) => { ... }


Enumerate the parameters (param1, param2, ..., paramN) , then put the arrow =>, and on the right side write the body { ... }.

Almost everywhere you can use a regular function, you can also use the arrow function. For example:


const numbers = [4, 5, 2, 6];

const doubled = numbers.map((number) => {

return number * 2;

});

doubled; // => [8, 10, 4, 12]


(number) => { return number * 2; } is an arrow function used as a callback of number.map() method.

2. this value

The arrow function resolves this lexically.

The biggest difference between an arrow function and regular function is that this value inside of an arrow function always equals to this from the outer function.

In other words, the arrow function doesn't define its own execution context.

In the following example, an arrow function is defined inside a method:


const object = {

items: [1, 2],

method() {

this === object; // => true

this.items.forEach(() => {

this === object; // => true

});

}

};

object.method();


myObject.myMethod([1, 2, 3]) is a method invocation. this value inside the arrow function equals to this of the outer function — and is object.

this resolved lexically is a great feature of arrow functions. When using callbacks inside methods you are sure the arrow function doesn't define its own this.

To compare, if you use a regular function under the same circumstance:


const object = {

items: [1, 2],

method() {

this === object; // => true

this.items.forEach(function () {

this === object; // => false

this === window; // => true

});

}

};

object.method();


Then inside of the regular function this equals the global object, which is window in a browser environment.

3. arguments object

The arrow function resolves arguments lexically.

The arguments object inside of an arrow function equals to arguments of the outer function.

Let's try to access arguments inside of an arrow function:


function regular() {

const arrow = () => {

arguments; // => ['A', 'B']

};

arrow('C');

}

regular('A', 'B');


arguments object inside the arrow function equals to the arguments of regular() function invocation: 'A', 'B'.

To access the direct arguments of the arrow function use a rest parameter ...args:


function regular() {

const arrow = (...args) => {

args; // => ['C']

}

arrow('C');

}

regular('A', 'B');


...args rest parameter collects the arguments of the arrow function invocation: ['C'].

4. Shortening

In the previous examples, the arrow function was used in the long form: both parentheses and curly braces were present.

Fortunately, a great benefit of the arrow function is the possibility to make it shorter. Let's see the situations when you can do that.

4.1 Omitting parenthesis

If the arrow function has one parameter, the parentheses around this parameter can be omitted:


(param) => { ... }

// can be simplified to:

param => { ... }


For example, the greet function has only one parameter who. That's good because you can omit the parentheses around the one parameter:


const greet = who => {

return `Hello, ${who}!`;

};

greet('Eric Cartman'); // => 'Hello, Eric Cartman!'


But be aware that parentheses cannot always be omitted.

If the arrow function accepts a rest parameter, destructures the parameter or has no parameters, then you have to keep the parentheses:


const greetObject = ({ name }) => {

return `Hello, ${name}!`;

}

const greetPeople = (...args) => {

return `Hello, ${args.join(' and ')}!`;

}

const sayHello = () => {

return 'Hello!';

}

greetObject({ name: 'Eric' }); // => 'Hello, Eric!'

greetPeople('Eric', 'Stan'); // => 'Hello, Eric and Stan!'

sayHello(); // => 'Hello!'


4.2 Omitting curly braces

If the arrow function body contains one statement, you can omit the curly braces and and return keyword, then the expression will be implicitely returned:


(param1, param2, ..., paramN) => { return statement; }

// can be simplified to:

(param1, param2, ..., paramN) => statement


Following the example, the greet function contains one statement, so let's omit the curly braces around the function body:


const greet = who => `Hello, ${who}!`;

greet('Eric Cartman'); // => 'Hello, Eric Cartman!'


In the arrow function who => `Hello, ${who}!` the expression `Hello, ${who}!` is implicitely returned.

The form when the curly braces are omitted is named an inline arrow function. They're useful for writing short callbacks:


const numbers = [4, 5, 2, 6];

const duplicated = numbers.map(number => number * 2);

duplicated; // => [8, 10, 4, 12]


Object literal case

Omitting the curly braces works flawlessly most of the time but with one exception.

When returning an object literal, you have to wrap the literal into a pair of parentheses:


const greetObject = who => ({ message: `Hello, ${who}!` });

greetObject('Eric Cartman'); // => { message: `Hello, Eric Cartman!` }


Otherwise, JavaScript confuses the curly braces of the function body with those of the object literal and returns undefined:


const greetObject = who => { message: `Hello, ${who}!` };

greetObject('Eric Cartman'); // => undefined


5. Dos and don'ts

5.1 Can be asynchronous

You can make an arrow function asynchornous using the async/await syntax:


const fetchMovies = async () => {

const response = await fetch('/api/movies');

const movies = await response.json();

return movies;

};

fetchMovies().then(movies => {

// Movies fetched

})


5.2 Cannot be a method

A method is a special function attached to an object. Inside a method, this value equals the object upon which the method was called on.

Let's consider the method isEmpty() in the collection object:


const collection = {

items: [1, 2, 3],

isEmpty() {

this === collection; // => true

return this.items.length === 0;

}

};

collection.isEmpty(); // => false


collection.isEmpty() is a method invocation. Inside of the method isEmpty(), you can access the special value this, which equals to the object upon which the method was called — collection.

However, from a previous section you know that this inside of an arrow function equals to this value of from the outer scope. That's why you normally cannot use an arrow function as a method:


const collection = {

items: [1, 2, 3],

isEmpty: () => {

this === collection; // => false

this === window; // => true

return this.items.length === 0;

}

};

collection.isEmpty(); // throws "TypeError: this.items is undefined"


When performing a method invocation collection.isEmpty() JavaScript throws a "TypeError this.items is undefined". All because this inside of the arrow function equals to the global object, particularly window when running in a browser.

5.3 Cannot be a constructor

A regular function can be a constructor of instances:


function User(name) {

this.name = name;

}

const user = new User('Eric Cartman');

user instanceof User; // => true


However, the arrow function cannot be used as a constructor:


const User = (name) => {

this.name = name;

}

const user = new User('Eric Cartman');

// throws "TypeError: User is not a constructor"


When User is an arrow function, invoking new User('Eric Cartman') throws a TypeError.

5.4 Cannot be a generator function

Finally, the arrow function cannot be used as generator function:


const getNumbersArrow = *() => {

yield 1;

yield 2;

};

// SyntaxError: Unexpected token '*'


When using an asterisk * to mark an arrow function as a generator, JavaScript throws a syntax error.

The regular functions, of course, are marked as generators without issues:


function *getNumbersRegular() {

yield 1;

yield 2;

}

// Works!

const gen = getNumbersRegular();

gen.next(); // => { value: 1, done: false }

gen.next(); // => { value: 2, done: false }

gen.next(); // => { value: undefined, done: true }


6. Summary

The central symbol of an arrow function is the fat arrow =>: on the left side of it are the params, and on the right side is the function body:


(param1, param2, ..., paramN) => { ... }


The arrow function can be shortened: when it has one parameter you can omit the parentheses param => { ... }, and when it has one statement you can omit the curly braces param => statement.

this and arguments inside of an arrow function are resolved lexically, meaning that they're taken from the outer function scope.

The arrow function has a few limitations: you cannot use it as a method on an object, constructor, or generator function.

Arrow functions are lightweight, inline, and easy to read (when not being nested too much) — use them as much as you want in your code.

What about the differences between an arrow and a regular function? Follow my post 5 Differences Between Arrow and Regular Functions to find a detailed answer.

Do you prefer using the arrow or regular functions?