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

213
Visualizações
Why does this function returns the last argument when called right after definition
function foo(x) {
  return x;
}
foo(1); // returns 1 as expected

function bar(x) {
  return x;
}(1,2,3); // returns 3

I couldn't understand why does bar function returns the last argument. Can anyone explain it to me?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your bar() function is being interpreted as a function declaration and not as a function expression, as a result, the (1, 2, 3) is not the call syntax for functions (), but rather the grouping operator using the comma-operator, which returns the last value of 3 (which is then logged in the console). If it's on separate lines it may become clearer:

function bar(x) { // declares a function bar
  console.log("running"); // never logged
  return x;
}
// Uses the grouping operator `( )`, with the comma operator
(1,2,3); // returns 3

If you make bar() a function expression, then it will behave as expected (here I'm using the unary plus + to achieve that):

+function bar(x) {
  console.log("running"); // logged
  return x;
}(1,2,3); // returns 1

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