Home > Mobile >  I expect this code to return undefined but it return function instead
I expect this code to return undefined but it return function instead

Time:06-13

I expect this code to return undefined but it return function instead can anyone tell me as I am new in js.

function createGreeter(greeting){
        function greet(){
            console.log(greeting,name)
        }
        return greet
    }
    
    let g1=createGreeter('Good Morning')
    console.log(typeof g1)
    let g2=createGreeter('Good Evening')

CodePudding user response:

You are returning inside the function greet the function itself

If you want to store in a var the result of greet function then you must call it:

Instead of return greet you should return greet()

CodePudding user response:

The code says return greet on line 5. The value of greet is the function greet itself. You may want to change line 5 to return greet(), which would execute the greet() function and then return the return value of greet(), which itself is undefined.

CodePudding user response:

So it looks like you want to create a function that accepts a greeting but returns another function that accepts a name (while maintaining a pointer to the variable (greeting) in its outer lexical environment when its returned) and returns the result of joining up those strings when it's called.

// `createGreeter` accepts a string and
// returns a new function that accepts a name
// and when that function is called ties both strings together
function createGreeter(greeting) {
  return function (name) {
    return `${greeting}, ${name}.`;
  }
}

// Both of these return a function that accepts a name
const goodevening = createGreeter('Good evening');
const expectingyou = createGreeter('I\'ve been expecting you');

// And now we just need to call those functions with the name
console.log(goodevening('Blofeld'));
console.log(expectingyou('Mr. Bond'));

  • Related