{statements;};", which is more convenient to apply; 2. It can return implicitly; 3. More intuitive scope and this binding ( do not bind this)."/> {statements;};", which is more convenient to apply; 2. It can return implicitly; 3. More intuitive scope and this binding ( do not bind this).">
search
HomeWeb Front-endFront-end Q&AWhat are the advantages of es6 arrow functions?

What are the advantages of es6 arrow functions?

Mar 07, 2022 pm 05:11 PM
es6advantagearrow function

es6 Advantages of arrow functions: 1. Concise syntax, such as "parameters => {statements;};", which is more convenient to apply; 2. Ability to return implicitly; 3. More intuitive function Binding of domain and this (does not bind this).

What are the advantages of es6 arrow functions?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

We all know that there are many ways to define functions in JavaScript. The most common one is to use the function keyword:

// 函数声明
function sayHi(someone) {
  return `Hello, ${someone}!`;
}
// 函数表达式
const sayHi = function(someone) {
  return `Hello, ${someone}`;
}

The function declaration and function expression above are called regular functions.

There is also the new arrow function syntax in ES6:

const sayHi = (someone) => {
  return `Hello, ${someone}!`;
}

Compared with the functions in the original JS, the arrow functions added in ES6 are more concise and more convenient to apply.

Advantages of es6 arrow function:

1. Concise syntax

Take an array and double it before outputting it.

删掉一个关键字,加上一个胖箭头;
没有参数加括号,一个参数可选择;
多个参数逗号分隔,

const numbers = [5,6,13,0,1,18,23];
//原函数
const double = numbers.map(function (number) {
    return number * 2;
})
console.log(double);
//输出结果
//[ 10, 12, 26, 0, 2, 36, 46 ]
//箭头函数     去掉function, 添加胖箭头
const double2 = numbers.map((number) => {
    return number * 2;
})
console.log(double2);
//输出结果
//[ 10, 12, 26, 0, 2, 36, 46 ]
//若只有一个参数,小括号能够不写(选择)
const double3 = numbers.map(number => {
    return number * 2;
})
console.log(double3);
//如有多个参数,则括号必须写;若没有参数,()须要保留
const double4 = numbers.map((number,index) => {
    return `${index}:${number * 2}`;  //模板字符串
})
console.log(double4);

2. Able to return implicitly

The displayed return is svg

const double3 = numbers.map(number => {
    return number * 2;  
    //return 返回内容;
})

The implicit return of arrow function is function

当你想简单返回一些东西的时候,以下:去掉return和大括号,把返回内容移到一行,较为简洁;
const double3 = numbers.map(number => number * 2);

Supplement: Arrow function is If an anonymous function needs to be called, it must be assigned to a variable, such as double3 above. Anonymous functions are useful when recursing and unbinding functions.

3. A more intuitive binding of scope and this (Does not bind this)

An object, we originally wrote this# in the function

##An object, we originally wrote this in the function

const Jelly = {
    name:'Jelly',
    hobbies:['Coding','Sleeping','Reading'],
    printHobbies:function () {
        this.hobbies.map(function (hobby) {
            console.log(`${this.name} loves ${hobby}`);
        })
    }
}
Jelly.printHobbies();
// undefined loves Coding
// undefined loves Sleeping
// undefined loves Reading

This means that the pointing of this.hobbies is correct, and the pointing of this.name is incorrect;

When an independent function is executed, this points to window

If we want to point correctly, our original approach is to set a variable to replace spa

//中心代码
printHobbies:function () {
    var self = this; // 设置变量替换
    this.hobbies.map(function (hobby) {
        console.log(`${self.name} loves ${hobby}`);
    })
}
Jelly.printHobbies();
// Jelly loves Coding
// Jelly loves Sleeping
// Jelly loves Reading
在ES6箭头函数中,咱们这样写code
//中心代码
printHobbies:function () {
   this.hobbies.map((hobby)=>{
       console.log(`${this.name} loves ${hobby}`);
   })
}
// Jelly loves Coding
// Jelly loves Sleeping
// Jelly loves Reading

This is because this is accessed in the arrow function In fact, it is inherited from this in its parent scope. The arrow function's own this does not exist. This is equivalent to the arrow function's this being determined when it is declared (lexical scope). The point of this It does not change when the method is called.

【Related recommendations:

javascript video tutorial, web front-end

The above is the detailed content of What are the advantages of es6 arrow functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.