Default Argument

Default Argument

Double function with a parameter numberOfTimes means that a function is passed as an argument to the number of times it will be invoked that parameter numberOfTimes Example
console.log(double(10)) => we don’t have to give another parameter because it is 1 per default.
Solution: 20
console.log(double(10,2)) => 40

let double = (x, numberOfTimes = 1) => {
  let result = x;
  
  for (let _ of new Array(numberOfTimes).fill()) {
    result *= 2;
  }
  
  return result;
}

console.log(double(10))

We have a function called double with parameters x and numberOfTimes and local variable result = x .

Then we iterate using for of loop with instanciating new Array(numberOfTimes).fill()) and the variable result = 2;

In the end we *return result

comments powered by Disqus