Reputation: 2814
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*/) => {
}
Upvotes: 0
Views: 1401
Reputation: 56
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
}
Upvotes: 0