Home > Net >  Javascript Closure - Why isn't undefined displayed?
Javascript Closure - Why isn't undefined displayed?

Time:11-20

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

CodePudding user response:

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.

CodePudding user response:

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