Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda