0

I am trying to implement the JavaScript code below so it uses a closure to return the response

(function() {
    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!"); 
    }

    console.log(hello('John', 33)); 
}();

1 Answers1

1

The code you posted is a Self-executing Anonymous Function, not a Closure. In fact there are no closures in your code at all because no variables' scopes cross function boundaries.

If you want to return a value from an SEAF, just add a return statement:

const message = (function() {
    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!"; 
    }

    const result = hello('John', 33);
    console.log( result ); 
    return result;
}();

If you want to export the hello function through the SEAF as a new function without any parameters (because the parameters are captured inside the returned lambda i.e. an example of Partial Application, then do this:

const hello = (function() {

    function hello(name, age) {
        return name + ", who is " + age + " years old, says hi!"; 
    }

    return () => hello('John', 33);
}());

console.log( hello() ); // will print  "John, who is 33 years old, says hi!" to the console.
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Thanks, but it should use a closure in the answer is what I was trying to say* –  Feb 19 '20 at 01:26
  • 1
    @tjhunt I think you don't understand what a closure is - or at least you aren't interpreting your task correctly. – Dai Feb 19 '20 at 01:27