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

推荐订阅源

F
Full Disclosure
The Register - Security
The Register - Security
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
V
Visual Studio Blog
H
Help Net Security
S
Secure Thoughts
U
Unit 42
P
Palo Alto Networks Blog
A
About on SuperTechFans
S
Securelist
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
The Cloudflare Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Scott Helme
Scott Helme
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
P
Proofpoint News Feed
T
Tor Project blog
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 聂微东
C
CERT Recently Published Vulnerability Notes
阮一峰的网络日志
阮一峰的网络日志
P
Privacy International News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
量子位
Security Latest
Security Latest
L
LangChain Blog
The Last Watchdog
The Last Watchdog
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
有赞技术团队
有赞技术团队
Know Your Adversary
Know Your Adversary
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - 三生石上(FineUI控件)
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
博客园 - 司徒正美
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Latest news
Latest news
S
Schneier on Security
H
Hacker News: Front Page

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 Getting Started with Arrow Functions in JavaScript 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()
Arrow Functions Shortening Recipes in JavaScript
Dmitri Pavlutin · 2019-07-30 · via Dmitri Pavlutin Blog

With fat arrow syntax you can define functions shorter than a function expression. There are cases when you can completely omit:

  • parameters parentheses (param1, param2)
  • return keyword
  • or even curly braces { }.

Let's explore how to make arrow functions concise and straightforward to read. Plus you'll find some tricky shortening cases to be aware of.

1. Basic syntax

An arrow function declaration in its full version consists of:

  • a pair of parentheses with the params enumerated (param1, param2)
  • followed by an arrow =>
  • ended with the function body { FunctionBody }

A typical arrow function looks as follows:


const sayMessage = (what, who) => {

return `${what}, ${who}!`;

};

sayMessage('Hello', 'World'); // => 'Hello, World!'


One small nuance here: you can't put a newline between the parameters (param1, param2) and the arrow =>.

Let's see how the arrow function can be shortened, making the function easy to read, almost inline. Such readability is convinient when dealing with callbacks.

2. Reducing parameters parentheses

The following function greet has just one parameter:


const greet = (who) => {

return `${who}, Welcome!`

};

greet('Aliens'); // => "Aliens, Welcome!"


greet arrow function has only one parameter who. This parameter is wrapped in a pair of parentheses (who).

When the arrow function has only one parameter, you can omit the parameters parentheses.

Let's use this possibility and simplify greet:


const greetNoParentheses = who => {

return `${who}, Welcome!`

};

greetNoParentheses('Aliens'); // => "Aliens, Welcome!"


The new version of the arrow function greetNoParentheses doesn't have parentheses around its single parameter who. Two characters less: still a win.

While this simplification is easy to grasp, there are a few exceptions when you have to keep the parentheses. Let's see these exceptions.

2.1 Be aware of default param

If the arrow function has one parameter with a default value, you must keep the parentheses.


const greetDefParam = (who = 'Martians') => {

return `${who}, Welcome!`

};

greetDefParam(); // => "Martians, Welcome!"


who parameter has a default value 'Martians'. In such a case, you must keep the pair of parentheses around the single parameter: (who = 'Martians').

2.2 Be aware of param destructuring

You must also keep the parentheses around a destructured parameter:


const greetDestruct = ({ who }) => {

return `${who}, Welcome!`;

};

const race = {

planet: 'Jupiter',

who: 'Jupiterians'

};

greetDestruct(race); // => "Jupiterians, Welcome!"


The only parameter of the function uses destructuring { who } to access the object's property who. In this case, you must wrap the destructuring in parentheses: ({ who }).

2.3 No parameters

When the function has no parameters, the parentheses are required as well:


const greetEveryone = () => {

return 'Everyone, Welcome!';

}

greetEveryone(); // => "Everyone, Welcome!"


greetEveryone doesn't have any parameters. The params parentheses () are kept.

3. Reducing curly braces and return

When the arrow function body consists of only one expression, you can remove the curly braces { } and return keyword.

Don't worry about omitting return. The arrow function implicitly returns the expression evaluation result.

That's the simplification I like the most in the arrow function syntax.

greetConcise function that doesn't have the curly braces { } and return:


const greetConcise = who => `${who}, Welcome!`;

greetConcise('Friends'); // => "Friends, Welcome!"


greetConcise is the shortest version of the arrow function syntax. The expression `${who}, Welcome!` is implicitly returned, even without return being present.

3.1 Be aware of object literal

When using the shortest arrow function syntax, and returning an object literal, you might experience an unexpected result.

Let's see what happens in such case:


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

greetObject('Klingons'); // => undefined


Being expected that greetObject returns an object, it actually returns undefined.

The problem is that JavaScript interprets the curly braces { } as function body delimiter, rather than an object literal. message: is interpreted as a label identifier, rather than a property.

To make the function return an object, wrap the object literal into a pair of parentheses:


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

greetObject('Klingons'); // => { message: `Klingons, Welcome!` }


({ message: `${who}, Welcome!` }) is an expression. Now JavaScript sees this as an expression containing an object literal.

4. Fat arrow method

Class Fields Proposal (as of August 2019 at stage 3) introduces the fat arrow method syntax to classes. this inside such a method always binds to the class instance.

Let's define a class Greet containing a fat arrow method:


class Greet {

constructor(what) {

this.what = what;

}

getMessage = (who) => {

return `${who}, ${this.what}!`;

}

}

const welcome = new Greet('Welcome');

welcome.getMessage('Romulans'); // => 'Romulans, Welcome!'


getMessage is a method in Greet class defined using the fat arrow syntax. this inside getMessage method always binds to the class instance.

Can you write concise fat arrow methods? Yes, you can!

Let's shorten getMessage method:


class Greet {

constructor(what) {

this.what = what;

}

getMessage = who => `${who}, ${this.what}!`

}

const welcome = new Greet('Welcome');

welcome.getMessage('Romulans'); // => 'Romulans, Welcome!'


getMessage = who => `${who}, ${this.what}!` is a concise fat arrow method definition. The pair of parentheses around its single param who was omitted, as well as the curly braces { } and return keyword.

5. Concise is not always readable

I enjoy concise arrow functions for the ability to instantly expose what the function does.


const numbers = [1, 4, 5];

numbers.map(x => x * 2); // => [2, 8, 10]


x => x * 2 easily implies a function that multiplies a number by 2.

While it might be tempting to use the short syntax as much as possible, it must be done wisely. Otherwise you might end up in a readability issue, especially in the case of multiple nested concise arrow functions.

JavaScript code Readability

I favor readability over brevity, so sometimes I would deliberately keep the curly braces and return keyword.

Let's define a concise factory function:


const multiplyFactory = m => x => x * m;

const double = multiplyFactory(2);

double(5); // => 10


While multiplyFactory is short, it might be difficult to understand at first glance what it does.

In such a case, I would avoid the shortest syntax and make the function definition a bit longer:


const multiplyFactory = m => {

return x => x * m;

};

const double = multiplyFactory(2);

double(5); // => 10


In the longer form, multiplyFactory is easier to understand that it returns an arrow function.

Anyways, you might have your taste. But I advise you to prioritize readability over passionate shortening.

6. Conclusion

The arrow function is known for its ability to provide short definitions.

Using the recipes presented above, you can shorten arrow functions by removing the params parentheses, curly braces or return keyword.

You can use these recipes with the upcoming fat arrow methods in classes.

However, shortening is good as long as it increases readability. If you have many nested arrow functions, it might be wise to avoid the shortest possible forms.

What JavaScript shortening techniques do you know? Please write a comment below!