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

151
Vistas
JavaScript define function to take outer function parameter

I want to define a function:

const f = (outside, param1, param2) => {
  outside(param1, param2);
}

But I know this function will always be called inside a function which has outside as parameter. For example:

const g = (outside, param3, param4) => {
  // some code here

  f(outside, var1, var2);

  // some more code
}

Is there any way to define f so that I dont need to pass outside to it when calling inside g?

Also I want to be able to call f inside other functions who take outside as parameter, not just g.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Is there any way to define f so that I dont need to pass outside to it when calling inside g?

No. You are asking for dynamic scope but JavaScript uses lexical scope. That means the availability/visibility of symbols is determined by the way functions are defined, not how/when/where they are called.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can change the order of the arguments and take action depending on their existence:

const f = (param1, param2, outside) => {
  if (outside) {
    outside(param1, param2);
  } else {
    ...
  }
}

UPDATE

Unfortunately a function defined outside of function g, will not have direct access to the variables contained in function g. For this reason, you must necessarily pass the parameter outside to function f.

about 4 years ago · Juan Pablo Isaza Denunciar

0

And if you change your logic like this? Will it fit your needs?

// Set function logic
const f = (param1, param2) => {
  return param1 + param2;
}

// Outside method
const outside = v => {
  console.log(`I'm outside: ${v}`);
}

// Call from outside logic
const g = (outside, param3, param4) => {
  // If you know, that it is outside wrapper, wrap it here
  outside(f(param3, param4));
}
g(outside, 2, 2);

// Call from else logic
console.log(`I'm else logic: ${f(3, 3)}`);

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