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*/) => {
}
fruit1tofruit5" - 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.function myFunc(...arr) { if (arr.length != 5) throw new RangeError("Needs 5 arguments for some reason"); … }