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*/) => {
}
4
  • 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: typescriptlang.org/play?#code/… Commented Jul 26, 2021 at 1: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. Commented Jul 26, 2021 at 1:25
  • Alternative 3: function myFunc(...arr) { if (arr.length != 5) throw new RangeError("Needs 5 arguments for some reason"); … } Commented Jul 26, 2021 at 1:27
  • 1
    Does this answer your question? Getting arguments passed to an ES6 arrow function using arguments variable Commented Jul 26, 2021 at 1:28

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

I believe they are looking for something what would show how many parameters the function is expecting...this is not very visual.
Then the best way is use Typescript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.