Characteristics of JavaScript arrow functions and differences from ordinary functions

Characteristics of JavaScript arrow functions and differences from ordinary functions

1. Use of arrow functions

ES6 adds a new method of defining function expressions using arrows => . In many cases , there is no difference between the functions created by arrow functions and function expressions, the only difference is the way they are written.

The second part of this article will introduce the functional differences between arrow functions and ordinary functions.

1. From normal function to arrow function

As shown below, to define a function, you can use function keyword. The function receives two parameters a and b and returns the sum of a and b .

function getSum(a, b) {
    return a + b;
}

If you use an arrow function to define this function, you can write it as follows, omitting the function keyword and using an arrow => to define a function.

const getSum = (a, b) => {
    return a + b;
};

2. Omit curly braces and return

If you define an arrow function and there is only a return statement in the function body, you can omit the curly braces {} and return .

As shown below, the complete definition of the arrow function.

const getSum = (a, b) => {
    return a + b;
};

This arrow function has only a return statement in its body. The simplified notation after omitting the curly braces {} and return is as follows:

const getSum = (a, b) => a + b;

3. Omit parentheses

If the defined arrow function has only one parameter, the parentheses can be omitted.

As shown below, the defined arrow function has only one parameter and is written in full.

const func = (a) => {
    return a + 2;
};

The parentheses around the parameters are omitted, and the following code is equivalent to the above code.

const func = a => a + 2;

Note : If the function has no parameters, or has multiple parameters, parentheses must be used.

2. The difference between arrow functions and normal functions

In most cases, arrow functions can be used wherever ordinary functions can be used, because arrow functions are more concise.

But in some cases, arrow functions are very different from ordinary functions.

1. The this of the arrow function is the this of the parent scope

The following code defines an object obj , which has a method getThis defined as a normal function, which prints out this here. Calling obj.getThis() will print out the obj object. This means that this inside the method points to the object obj .

const obj = {
    name: 'Jack',
    getThis() {
        console.log(this);
    },
};
obj.getThis(); // {name: 'Jack', getThis: ƒ}

Similarly, an object obj is defined, but the method inside it is defined with an arrow function. When obj.getThis() is called in the browser, Window is printed. This shows that even if the method on the obj object is called, this inside the method will not point to obj , but to this of the context in which obj is defined.

const obj = {
    name: 'Jack',
    getThis: () => {
        console.log(this);
    },
};
obj.getThis(); // Window

2. call, apply, and bind cannot change the this of arrow functions

In the following code, the ordinary function getName prints this.name , binds this in the function to obj through call , and calls getName to print out the attribute name on obj .

const obj = {
    name: 'Jack',
};

function getName() {
    console.log(this.name);
}
getName.call(obj); // Jack

If the function is changed to an arrow function, call will not work, and this inside the function cannot be bound to obj , and undefined will be printed.

const obj = {
    name: 'Jack',
};

const getName = () => {
    console.log(this.name);
};
getName.call(obj); // undefined

3. Cannot be used as a constructor

Arrow functions cannot be used as constructors. If you use an arrow function as a constructor, an error will be reported, as shown in the following code.

const Person = () => {
    this.name = 'Jack';
};
const usr = new Person(); // Person is not a constructor

4. No arguments

Inside a normal function, you can use arguments to get the passed in parameters, which is an array-like object:

function func() {
    console.log(arguments);
}
func(1, 2, 3); // [Arguments] { '0': 1, '1': 2, '2': 3 }

However, arrow functions cannot use the arguments object and cannot obtain input parameters.

In the browser, if you use arguments object in an arrow function, an error will be reported.

const func = () => {
    // Browser environment console.log(arguments); // arguments is not defined
};
func(1, 2, 3);

However, the arrow function can obtain the input parameters in the form of ...args within the parameters, and the obtained args is an array.

const func = (...args) => {
    console.log(args); // [ 1, 2, 3 ]
};
func(1, 2, 3);

5. Arrow functions do not support new.target

Inside the constructor of a normal function definition, new.target is supported to return the constructor that constructs the instance.

function Person() {
    this.name = 'Jack';
    console.log(new.target);
}
// Points to the constructor new Person(); // [Function: Person]

In arrow functions, new.target is not supported. In the browser environment, arrow functions using new.target new.target expression is not allowed here .

const Person = () => {
    this.name = 'Jack';
    console.log(new.target);
}
// Browser environment new Person(); // new.target expression is not allowed here

References for this article:

Advanced JavaScript Programming (4th Edition)

This concludes this article about the characteristics of JavaScript arrow functions and the differences from ordinary functions. For more information about js arrow functions and ordinary functions, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Tips for writing better JavaScript conditionals and matching conditions (summary)
  • Detailed explanation of this pointing in JS arrow function
  • Detailed explanation of the difference between arrow functions and normal functions in JavaScript
  • What scenarios are not suitable for JS arrow functions?
  • Which scenarios in JavaScript cannot use arrow functions
  • Introduction to JavaScript conditional access attributes and arrow functions

<<:  Two ways to implement square div using CSS

>>:  HTML small tag usage tips

Recommend

Ubuntu 20.04 turns on hidden recording noise reduction function (recommended)

Recently, when using kazam in Ubuntu 20.04 for re...

Basic usage of wget command under Linux

Table of contents Preface 1. Download a single fi...

JavaScript canvas realizes the effect of nine-square grid cutting

This article shares the specific code of canvas t...

Use of Linux date command

1. Command Introduction The date command is used ...

A thorough analysis of HTML special characters

A Thorough Analysis of HTML (14) Special Characte...

MySQL 5.7.30 Installation and Upgrade Issues Detailed Tutorial

wedge Because the MySQL version installed on the ...

MySQL 8.0.17 installation and simple configuration tutorial under macOS

If you don’t understand what I wrote, there may b...

Node.js+postman to simulate HTTP server and client interaction

Table of contents 1. Node builds HTTP server 2. H...

Summary of MySql storage engine and index related knowledge

Storage Engine What is a database storage engine?...

Detailed explanation of Vite's new experience

What is Vite? (It’s a new toy on the front end) V...

Nginx installation error solution

1. Unzip nginx-1.8.1.tar.gz 2. Unzip fastdfs-ngin...

Detailed explanation of the basic commands of Firewalld firewall in Centos7

1. Basics of Linux Firewall The Linux firewall sy...

WeChat applet custom bottom navigation bar component

This article example shares the specific implemen...