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

186
Views
unpacking rest (...theArgs) parameter before passing it to the function

I am trying to call a function required number of times. To solve this, I am creating a function that takes rest parameters and iterating through the first argument. I am unable to unpack the rest arguments and pass it to the function. Is there a way that I could unpack and pass it to the function as parameters. Below is my working code. Is there a better way to make it work ? Thanks in advance. Appreciate any help.

function hello(name) {
  console.log("Hello "+ name);
}

function greet(name,time_of) {
  console.log("Good " + time_of +" " +name);
}

function foo(times,x, ...args) {
    for(i=0;i<times;i++) {
    x(arguments)
    //x(args); //works good for hello() but not for greet(). Doesn't pass them to second argument
    x(args[0],args[1]); //This works but not scalable 
    //args.map((element) => x(element)); 

  }
}

foo(2,hello,"Myname");
foo(3,greet,"Myname","Afternoon");
almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Just spread the args out again:

function hello(name) {
  console.log("Hello " + name);
}

function greet(name, time_of) {
  console.log("Good " + time_of + " " + name);
}

function foo(times, x, ...args) {
  for (i = 0; i < times; i++) {
    x(...args)
  }
}

foo(2, hello, "Myname");
foo(3, greet, "Myname", "Afternoon");

almost 4 years ago · Santiago Trujillo 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!