Run JavaScript Immediately Arrow Function Structure Question.

Asked 2 years ago, Updated 2 years ago, 92 views

Hello, nice to meet you.

I'm studying the arrow function of ES6.

There was a code example below, saying, "The arrow function can also be used as an immediate execution function."

const person = ( name => ({
    sayHi() { return `Hi? My name is ${name}.`; }
}))('Lee');

console.log(person.sayHi());  // Hi? My name is Lee.

In the code above, I know that the bracket to the left of the name parameter is the bracket that starts the execution function immediately, but to the right of the arrow, why is the body of the function wrapped in bracket again?

After searching, if the arrow function returns an object literal, the object literal must be wrapped in brackets (). That's what they say.

The arrow function returns a function called sayHi(), but in JavaScript, is it because the function is also an object?

Does sayHi() mean object literal in this case?

Thank you for reading!

javascript es6

2022-09-20 17:08

1 Answers

If you solve the code you used as an example, it looks like this.

const person = (function(name) {
    return {
        sayHi: function() {
            return `Hi? My name is ${name}`;
        }
    };
})('Lee');

In other words, the return value of the immediate execution function is an object with the sayHi function as a property, not the sayHi function.

To return a function, it has to be as below.

const sayHi = (name => () => `Hi? My name is ${name}`)('Lee');
console.log(sayHi());

For reference, the function that returns the function is called a high-order function and is a commonly used pattern.


2022-09-20 17:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.