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

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | 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 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()
When 'Not' to Use Arrow Functions
Dmitri Pavlutin · 2016-06-06 · via Dmitri Pavlutin Blog

It is a pleasure to see the evolution of the programming language you code every day. Learning from mistakes, searching for better implementation, creating new features is what makes the progress from version to version.

This is happening to JavaScript these years when ECMAScript 6 brings the language to a new level of usability: arrow functions, classes and a lot more. And this is great!

One of the most valuable new features is the arrow function. There are plenty of good articles that describe its context transparency and short syntax. If you're new to ES6, take a start from reading about it.

But every medal has two sides. Often new features introduce some confusion, one of which is the arrow functions misguided utilization.

This article guides through scenarios where you should bypass the arrow function in favor of good old function expressions or newer shorthand method syntax. And take precautions with shortening, because it can affect the code readability.

1. Defining methods on an object

In JavaScript, the method is a function stored in a property of an object. When calling the method, this becomes the object that the method belongs to.

1a. Object literal

Since arrow function has a short syntax, it's inviting to use it for a method definition. Let's take a try:


const calculate = {

array: [1, 2, 3],

sum: () => {

console.log(this === window); // => true

return this.array.reduce((result, item) => result + item);

}

};

console.log(this === window); // => true

// Throws "TypeError: Cannot read property 'reduce' of undefined"

calculate.sum();


calculate.sum method is defined with an arrow function. But on invocation calculate.sum() throws a TypeError, because this.array is evaluated to undefined.
When invoking the method sum() on the calculate object, the context remains window. It happens because the arrow function binds the context lexically with the window object.
Executing this.array is equivalent to window.array, which is undefined.

The solution is to use a function expression or shorthand syntax for method definition (available in ECMAScript 6). In such a case this is determined by the invocation, but not by the enclosing context. Let's see the fixed version:


const calculate = {

array: [1, 2, 3],

sum() {

console.log(this === calculate); // => true

return this.array.reduce((result, item) => result + item);

}

};

calculate.sum(); // => 6


Because sum is a regular function, this on invocation of calculate.sum() is the calculate object. this.array is the array reference, therefore the sum of elements is calculated correctly: 6.

1b. Object prototype

The same rule applies when defining methods on a prototype object.
Instead of using an arrow function for defining sayCatName method, which brings an incorrect context window:


function MyCat(name) {

this.catName = name;

}

MyCat.prototype.sayCatName = () => {

console.log(this === window); // => true

return this.catName;

};

const cat = new MyCat('Mew');

cat.sayCatName(); // => undefined


use the old school function expression:


function MyCat(name) {

this.catName = name;

}

MyCat.prototype.sayCatName = function() {

console.log(this === cat); // => true

return this.catName;

};

const cat = new MyCat('Mew');

cat.sayCatName(); // => 'Mew'


sayCatName regular function is changing the context to cat object when called as a method: cat.sayCatName().

2. Callback functions with dynamic context

this in JavaScript is a powerful feature. It allows changing the context depending on the way a function is called. Frequently the context is the target object on which invocation happens, making the code more natural. It says like "something is happening with this object".

However, the arrow function binds the context statically on the declaration and is not possible to make it dynamic. It's the other side of the medal in a situation when lexical this is not necessary.

Attaching event listeners to DOM elements is a common task in client-side programming. An event triggers the handler function with this as the target element. Handy usage of the dynamic context.

The following example is trying to use an arrow function for such a handler:


const button = document.getElementById('myButton');

button.addEventListener('click', () => {

console.log(this === window); // => true

this.innerHTML = 'Clicked button';

});


this is window in an arrow function that is defined in the global context. When a click event happens, browser tries to invoke the handler function with button context, but arrow function does not change its pre-defined context.
this.innerHTML is equivalent to window.innerHTML and has no sense.

You have to apply a function expression, which allows to change this depending on the target element:


const button = document.getElementById('myButton');

button.addEventListener('click', function() {

console.log(this === button); // => true

this.innerHTML = 'Clicked button';

});


When user clicks the button, this in the handler function is button. Thus this.innerHTML = 'Clicked button' modifies correctly the button text to reflect clicked status.

3. Invoking constructors

this in a construction invocation is the newly created object. When executing new MyFunction(), the context of the constructor MyFunction is a new object: this instanceof MyFunction === true.

Notice that an arrow function cannot be used as a constructor. JavaScript implicitly prevents from doing that by throwing an exception.
Anyway this is setup from the enclosing context and is not the newly created object. In other words, an arrow function constructor invocation doesn't make sense and is ambiguous.
Let's see what happens if however trying to:


const Message = (text) => {

this.text = text;

};

// Throws "TypeError: Message is not a constructor"

const helloMessage = new Message('Hello World!');


Executing new Message('Hello World!'), where Message is an arrow function, JavaScript throws a TypeError that Message cannot be used as a constructor.

I consider an efficient practice that ECMAScript 6 fails with verbose error messages in such situations. Contrary to fail silently specific to previous JavaScript versions.

The above example is fixed using a function expression, which is the correct way (including the function declaration) to create constructors:


const Message = function(text) {

this.text = text;

};

const helloMessage = new Message('Hello World!');

console.log(helloMessage.text); // => 'Hello World!'


4. Too short syntax

The arrow function has a nice property of omitting the arguments parenthesis (), block curly brackets {} and return if the function body has one statement. This helps in writing very short functions.

My university professor of programming gives students an interesting task: write the shortest function that counts the string length in C language. This is a good approach to study and explore a new language.

Nevertheless, in real-world applications, the code is read by many developers. The shortest syntax is not always appropriate to help your colleague understand the function on the fly.

At some level the compressed function becomes difficult to read, so try not to get into passion. Let's see an example:


const multiply = (a, b) => b === undefined ? b => a * b : a * b;

const double = multiply(2);

double(3); // => 6

multiply(2, 3); // => 6


multiply returns the multiplication result of two numbers or a closure tied with first parameter for later multiplication.
The function works nice and looks short. But it may be tough to understand what it does from the first look.

To make it more readable, it is possible to restore the optional curly braces and return statement from the arrow function or use a regular function:


function multiply(a, b) {

if (b === undefined) {

return function(b) {

return a * b;

}

}

return a * b;

}

const double = multiply(2);

double(3); // => 6

multiply(2, 3); // => 6


It is good to find a balance between short and verbose to make your JavaScript straightforward.

5. Conclusion

Without a doubt, the arrow function is a great addition. When used correctly it brings simplicity in places where earlier you had to use .bind() or trying to catch the context. It also makes the code lighter.

Advantages in some situations bring disadvantages in others. You can't use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.

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.