Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!