Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda