0

I was reading the book :

JavaScript The Definitive Guide

and got an issue in understanding an example code given in 8.3.4 as The Spread Operator for Function Calls.

Here's the code :

// This function takes a function and returns a wrapped version
function timed(f) {
 return function(...args) { // Collect args into a rest parameter array
 console.log(`Entering function ${f.name}`);
 let startTime = Date.now();
 try {
 // Pass all of our arguments to the wrapped function
 return f(...args); // Spread the args back out again
 }
 finally {
 // Before we return the wrapped return value, print elapsed time.
 console.log(`Exiting ${f.name} after ${Date.now()-startTime}ms`);
 }
};
}
// Compute the sum of the numbers between 1 and n by brute force
function benchmark(n) {
 let sum = 0;
 for(let i = 1; i <= n; i++) sum += i;
 return sum;
}

When Invoked gives this

// Now invoke the timed version of that test function
timed(benchmark)(1000000) 
Entering function benchmark
Exiting benchmark after 11ms
500000500000

My Problem

I am not able to understand what these 2 Js Statements are for and their working?

// 1st
return function(...args)

//2nd
return f(...args); 

I haven't seen any function like this without a name. Please help me in understanding.

Thanks

13
  • 1
    Does this answer your question? What is the meaning of "...args" (three dots) in a function definition? Commented Jul 27, 2021 at 10:15
  • Hi @aaandri98 No, My question is different. I know the use of spread operator. I can't understand this : return function(...args). What is function here. How can it be even that and not name of a function? Commented Jul 27, 2021 at 10:19
  • The function is named timed and it's using function here. Commented Jul 27, 2021 at 10:20
  • @Baazigar it's not the "spread operator". This is rest syntax for function parameters. Commented Jul 27, 2021 at 10:21
  • Sorry for my typo. I meant rest only. Commented Jul 27, 2021 at 10:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.