Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
I expect this code to return undefined but it return function instead

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')
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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'));

about 4 years ago · Juan Pablo Isaza Report

0

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()

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!