Home > Web Front-end > JS Tutorial > body text

Can You Name Arrow Functions in ES2015 Without `var`?

Susan Sarandon
Release: 2024-11-06 14:05:03
Original
711 people have browsed it

Can You Name Arrow Functions in ES2015 Without `var`?

How to Name Arrow Functions in ES2015

In ES6, you can enhance your code with arrow functions. However, when dealing with named functions, you may wonder if there's a way to assign a name to an arrow function without using a var statement.

Consider the following named function using the traditional syntax:

function sayHello(name) {
    console.log(name + ' says hello');
}
Copy after login

In ES6, we can convert this function to an arrow syntax as follows:

var sayHello = (name) => {
    console.log(name + ' says hello');
}
Copy after login

However, what if we want to name the arrow function without explicitly declaring it with var?

The answer lies in taking advantage of JavaScript's variable declaration behavior. By simply assigning an arrow function to a variable or property without using var, the JavaScript engine will automatically assign the name to the function.

sayHello = (name) => {
    console.log(name + ' says hello');
}
Copy after login

This approach creates a function with a true name, as demonstrated below:

console.log(sayHello.name); // "sayHello"
Copy after login

Remember, this technique is not limited to arrow functions; it also applies to traditional anonymous function expressions.

The above is the detailed content of Can You Name Arrow Functions in ES2015 Without `var`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!