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

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

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 How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
5 Differences Between Arrow and Regular Functions
Dmitri Pavlutin · 2020-05-16 · via Dmitri Pavlutin Blog

You can define JavaScript functions in many ways.

The first, usual way, is by using the function keyword:


// Function declaration

function greet(who) {

return `Hello, ${who}!`;

}



// Function expression

const greet = function(who) {

return `Hello, ${who}`;

}


The function declaration and function expression I'm going to reference as regular function.

The second way, available starting ES2015, is the arrow function syntax:


const greet = (who) => {

return `Hello, ${who}!`;

}


While both the regular and arrow syntaxes define functions, when would you use one or another? That's a good question.

In this post, I'll show you the difference between the two, so you could choose the right syntax for your needs.

Table of Contents

  • 1. this value
    • 1.1 Regular function
    • 1.2 Arrow function
  • 2. Constructors
    • 2.1 Regular function
    • 2.2 Arrow function
  • 3. arguments object
    • 3.1 Regular function
    • 3.2 Arrow function
  • 4. Implicit return
    • 4.1 Regular function
    • 4.2 Arrow function
  • 5. Methods
    • 5.1 Regular function
    • 5.2 Arrow function
  • 6. Summary

1. this value

1.1 Regular function

Inside a regular JavaScript function, this value (aka the execution context) is dynamic.

The dynamic context means that the value of this depends on how the function is invoked. In JavaScript, there are 4 ways you can invoke a regular function.

During a simple invocation the value of this equals the global object (or undefined if the function runs in strict mode):


function myFunction() {

console.log(this);

}

// Simple invocation

myFunction(); // logs global object (window)


During a method invocation the value of this is the object owning the method:


const myObject = {

method() {

console.log(this);

}

};

// Method invocation

myObject.method(); // logs myObject


During an indirect invocation using myFunc.call(thisVal, arg1, ..., argN) or myFunc.apply(thisVal, [arg1, ..., argN]) the value of this equals to the first argument:


function myFunction() {

console.log(this);

}

const myContext = { value: 'A' };

myFunction.call(myContext); // logs { value: 'A' }

myFunction.apply(myContext); // logs { value: 'A' }


During a constructor invocation using new keyword this equals the newly created instance:


function MyFunction() {

console.log(this);

}

new MyFunction(); // logs an instance of MyFunction


1.2 Arrow function

The behavior of this inside of an arrow function differs from the regular function's this behavior. The arrow function doesn't define its own execution context but resolves to the one from the outer function.

No matter how or where being executed, this value inside of an arrow function always equals this value from the outer function. In other words, the arrow function resolves this lexically.

In the following example, myMethod() is an outer function of callback() arrow function:


const myObject = {

myMethod(items) {

console.log(this); // logs myObject

const callback = () => {

console.log(this); // logs myObject

};

items.forEach(callback);

}

};

myObject.myMethod([1, 2, 3]);


this value inside the arrow function callback() equals this of the outer function myMethod().

this resolved lexically is one of the great features of the arrow functions. When using callbacks inside methods you are sure the arrow function doesn't define its own this (no more const self = this or callback.bind(this) workarounds).

Contrary to a regular function, the indirect invocation of an arrow function using myArrowFunc.call(thisVal) or myArrowFunc.apply(thisVal) doesn't change the value of this: the context value always resolves lexically.

2. Constructors

2.1 Regular function

As seen in the previous section, the regular function can easily construct objects.

For example, the new Car() function creates instances of a car:


function Car(color) {

this.color = color;

}

const redCar = new Car('red');

redCar instanceof Car; // => true


Car is a regular function. When invoked with new keyword new Car('red') — new instances of Car type are created.

2.2 Arrow function

A consequence of this resolved lexically is that an arrow function cannot be used as a constructor.

If you try to invoke an arrow function prefixed with new keyword, JavaScript throws an error meaning that an arrow function cannot be a constructor.


const Car = (color) => {

this.color = color;

};

const redCar = new Car('red'); // TypeError: Car is not a constructor


Invoking new Car('red'), where Car is an arrow function, throws TypeError: Car is not a constructor.

3. arguments object

3.1 Regular function

Inside the body of a regular function, arguments is a special array-like object containing the list of arguments with which the function has been invoked.

Let's invoke myFunction() function with 2 arguments:


function myFunction() {

console.log(arguments);

}

myFunction('a', 'b'); // logs { 0: 'a', 1: 'b', length: 2 }


Inside of myFunction() body the arguments is an array-like object containing the invocation arguments: 'a' and 'b'.

3.2 Arrow function

On the other side, no arguments special keyword is defined inside an arrow function.

Again (same as with this value), the arguments object is resolved lexically: the arrow function accesses arguments from the outer function.

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


function myRegularFunction() {

const myArrowFunction = () => {

console.log(arguments);

}

myArrowFunction('c', 'd');

}

myRegularFunction('a', 'b'); // logs { 0: 'a', 1: 'b', length: 2 }


The arrow function myArrowFunction() is invoked with the arguments 'c', 'd'. Still, inside of its body, arguments object equals the arguments of myRegularFunction() invocation: 'a', 'b'.

If you'd like to access the direct arguments of the arrow function, then you can use the rest parameters feature:


function myRegularFunction() {

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

console.log(args);

}

myArrowFunction('c', 'd');

}

myRegularFunction('a', 'b'); // logs ['c', 'd']


...args rest parameter collects the execution arguments of the arrow function into an array: ['c', 'd'].

4. Implicit return

4.1 Regular function

return expression statement returns the result from a function:


function myFunction() {

return 42;

}

myFunction(); // => 42


If the return statement is missing, or there's no expression after the return statement, the regular function implicitly returns undefined:


function myEmptyFunction() {

42;

}

function myEmptyFunction2() {

42;

return;

}

myEmptyFunction(); // => undefined

myEmptyFunction2(); // => undefined


4.2 Arrow function

You can return values from the arrow function the same way as from a regular function, but with one useful exception.

If the arrow function contains one expression, and you omit the function's curly braces, then the expression is implicitly returned. These are the inline arrow functions.


const increment = (num) => num + 1;

increment(41); // => 42


increment() consists of only one expression: num + 1. This expression is implicitly returned by the arrow function without the use of return keyword.

5. Methods

5.1 Regular function

Regular functions are the usual way to define methods on classes or objects.

In the following class Hero, the method logName() is defined using a regular function:


class Hero {

constructor(heroName) {

this.heroName = heroName;

}

logName() {

console.log(this.heroName);

}

}

const batman = new Hero('Batman');


Usually, regular functions as methods are the way to go.

Sometimes you'd need to supply the method as a callback, for example to setTimeout() or an event listener. In such cases, you might encounter difficulties accessing this value.

For example, let's use logName() method as a callback to setTimeout():


setTimeout(batman.logName, 1000);

// after 1 second logs "undefined"


After 1 second, undefined is logged to console. setTimeout() performs a simple invocation of logName (where this is the global object). That's when the method is separated from the object.

Let's bind this value manually to the right context:


setTimeout(batman.logName.bind(batman), 1000);

// after 1 second logs "Batman"


batman.logName.bind(batman) binds this value to batman instance. Now you're sure that the method doesn't lose the context.

Binding this manually requires boilerplate code, especially if you have lots of methods. There's a better way: the arrow functions as a class field.

5.2 Arrow function

Thanks to the class fields feature you can use the arrow function as methods inside classes.

Now, in contrast with regular functions, the method defined using an arrow binds this lexically to the class instance.

Let's use the arrow function as a field:


class Hero {

constructor(heroName) {

this.heroName = heroName;

}

logName = () => {

console.log(this.heroName);

}

}

const batman = new Hero('Batman');


Now you can use batman.logName as a callback without manual binding of this. The value of this inside logName() method is always the class instance:


setTimeout(batman.logName, 1000);

// after 1 second logs "Batman"


6. Summary

Understanding the differences between regular and arrow functions helps choose the right syntax for specific needs.

this value inside a regular function is dynamic and depends on the invocation. But this inside the arrow function is bound lexically and equals to this of the outer function.

arguments object inside the regular functions contains the arguments in an array-like object. The arrow function, on the opposite, doesn't define arguments (but you can easily access the arrow function arguments using a rest parameter ...args).

If the arrow function has one expression, then the expression is returned implicitly, even without using the return keyword.

Last but not least, you can define methods using the arrow function syntax inside classes. Fat arrow methods bind this value to the class instance.

Anyhow the fat arrow method is invoked, this always equals the class instance, which is useful when the methods are used as callbacks.

To understand all types of functions in JavaScript, I recommend checking JavaScript Function Declaration: The 6 Ways.

What other differences between the arrow and regular functions do you know?