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

How to forget the password of Jenkins in Linux

1.Jenkins installation steps: https://www.jb51.ne...

Detailed explanation of the process of modifying Nginx files in centos7 docker

1. Install nginx in docker: It is very simple to ...

Zabbix3.4 method to monitor mongodb database status

Mongodb has a db.serverStatus() command, which ca...

How to use MySQL common functions to process JSON

Official documentation: JSON Functions Name Descr...

HTML meta explained

Introduction The meta tag is an auxiliary tag in ...

HTML basic syntax is convenient for those who are just starting to learn HTML

1.1 General marking A general tag consists of an ...

Binary Search Tree Algorithm Tutorial for JavaScript Beginners

Table of contents What is a Binary Search Tree (B...

Detailed explanation of binary and varbinary data types in MySQL

Preface BINARY and VARBINARY are somewhat similar...

An article to help you learn more about JavaScript arrays

Table of contents 1. The role of array: 2. Defini...

TinyEditor is a simple and easy-to-use HTML WYSIWYG editor

A few days ago, I introduced to you a domestic xh...

MySQL slow query pt-query-digest analysis of slow query log

1. Introduction pt-query-digest is a tool for ana...

What to do if the container started by docker run hangs and loses data

Scenario Description In a certain system, the fun...

MySQL 8.0.11 Installation Guide for Mac

MAC installs mysql8.0, the specific contents are ...

How to use JS WebSocket to implement simple chat

Table of contents Short Polling Long-Polling WebS...

Three BOM objects in JavaScript

Table of contents 1. Location Object 1. URL 2. Pr...