0

I have an arrow function with exactly 5 arguments; fruit1 to fruit5. I want to make it clear it is just limited to those 5 arguments, so I do not want to use ... rest.

However, within the function I need to create an array from those five arguments.

const myFunc = (fruit1, fruit2, fruit3, fruit4, fruit5) => {
    let arr = [... arguments];
    // Other stuff follows
}

has the error that arguments is not defined (because arguments does not exist in arrow functions).

The alternative

const myFunc = (fruit1, fruit2, fruit3, fruit4, fruit5) => {
    let arr = [fruit1, fruit2, fruit3, fruit4, fruit5];
    // Other stuff follows
}

is cumbersome.

Rest does not make it clear there MUST be exactly 5 fruits to other programmers using the code:

const myFunc = (... rest) => {
    let arr = [... rest]; // A copy of the array
    // Other stuff follows
}

So what is best to do?

Edit:

For this project I cannot use typescript, but I think it is best to use some typescript terminology as suggested by @Nick, to indicated to future people looking at my code that 5 arguments are required. EG:

// type Elements = [object,object,object,object,object];
const myFunc = (... fruitARR /*:Element*/) => {
}
Rewind
  • 2,554
  • 3
  • 30
  • 56
  • Your second option seems best. It's verbose, but it does what you need it to do. Or move to typescript and you can enforce this quite easily: https://www.typescriptlang.org/play?#code/C4TwDgpgBAogNhAthAdsAzlAvFA2igV0QCMIAnAGkJPKqNLIF0BuAKFYGMB7FdYKAGYEUHbFAAUAOmlkIfAFywEyNOgCU2AHxQA3uwC+7ISPEBGClABMFgMwWALGuZA – Nick Jul 26 '21 at 01:08
  • "*I have an arrow function with exactly 5 arguments; `fruit1` to `fruit5`*" - you should never enumerate your variable names. Always use an array instead. Or are they actually different kinds of arguments? What are you doing with the fruits? Why do you need them in an array? Why do you need exactly 5 values? What is your actual code? We cannot give proper advice without answers to all these questions. – Bergi Jul 26 '21 at 01:25
  • Alternative 3: `function myFunc(...arr) { if (arr.length != 5) throw new RangeError("Needs 5 arguments for some reason"); … }` – Bergi Jul 26 '21 at 01:27
  • Does this answer your question? [Getting arguments passed to an ES6 arrow function using arguments variable](https://stackoverflow.com/questions/35368213/getting-arguments-passed-to-an-es6-arrow-function-using-arguments-variable) – MatthewProSkils Jul 26 '21 at 01:28

1 Answers1

0

If you dont want use ...rest, I think your alternative option is good and simple.

Other option can to be:

const myFunc = (fruits) => {
  if(!Array.isArray(fruits) || fruits.length != 5){
    alert("Is not array or not are 5 elements);
    throw "Error";     
  }
  // then fruits is your array
  // Other stuff
}