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

168
Views
Javascript Closure - Why isn't undefined displayed?

I'm trying to understand how closure works in Javascript. In the last line, if I enter sayHi("Hello")("John Doe"), the console would display "HelloJohn Doe" as expected.

Now, if I remove ("John Doe"), how come the console turns blank instead of displaying "Helloundefined"?

    function sayHi(whattosay){
        return function yolo(name) {
            console.log(whattosay + name)
        }
    }
    sayHi("Hello")
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

That's because you still need to call the function, even if you don't want to provide the "name" parameter.

Try with : sayHi("whatever")()

and you will see the expected output!

whateverundefined

If you omit the last pair of parenthesis, you are just getting back a function that WOULD print the expected output if you called it, but you just aren't calling it yet.

so you could for example store that returned function in some variable, and call it later on.

about 4 years ago · Juan Pablo Isaza Report

0

this will return your inner function yolo

function sayHi(whattosay){
    return function yolo(name) {
        console.log(whattosay + name)
    }
}
sayHi("Hello")

you need to call yolo function to see your console.log output

function sayHi(whattosay){
    return function yolo(name) {
        console.log(whattosay + name)
    }
}
sayHi("Hello")()

you can even store return function in a variable and call it

function sayHi(whattosay){
    return function yolo(name) {
        console.log(whattosay + name)
    }
}
const yolo = sayHi("Hello")

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