I expect this code to print undefined, but it prints function instead. Can anyone tell me why? 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')
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'));
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()
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.