0

I have a function that returns different values when I pass an array vs. a rest parameter. When I check each with Array.isArray(), they are both arrays. Why is the return value different?

function checkTerm(...terms) {

  var checkSet = ['that','this','else','now'];

  return terms.filter(term => checkSet.indexOf(term) > -1);
}

console.log(checkTerm(['this', 'them', 'else']));

VERSUS

function checkTerm(terms) {

  var checkSet = ['that','this','else','now'];

  return terms.filter(term => checkSet.indexOf(term) > -1);
}

console.log(checkTerm(['this', 'them', 'else']));

Passing Parameter as rest: Expected output = ['this','else'], Actual output = []

Passing Parameter as array: Expected output = ['this','else'], Actual output = ['this','else']

Ryan O'D
  • 340
  • 2
  • 10
  • Possible duplicate of [Usage of rest parameter and spread operator in javascript](https://stackoverflow.com/questions/20541339/usage-of-rest-parameter-and-spread-operator-in-javascript) – Heretic Monkey Oct 08 '19 at 18:22
  • Does this answer your question? [Spread Syntax vs Rest Parameter in ES2015 / ES6](https://stackoverflow.com/questions/33898512/spread-syntax-vs-rest-parameter-in-es2015-es6) – Henke Mar 15 '21 at 14:56
  • In the first example where I use the rest parameters, I'm putting an array into an array. That is the problem. It can be solved by just accepting the array or accepting the array as [...terms] rather than ...terms. – Ryan O'D Feb 04 '22 at 00:00

1 Answers1

2

In your first example you should have called the function like this:

console.log(checkTerm('this', 'them', 'else'));

The way you invoked it, terms is an array with a single element and that element is ['this', 'them', 'else'].

The "rest" operator is meant to convert separate parameters into an array so you should not pass an array directly to it (unless you want an array of arrays...).

dee-see
  • 23,668
  • 5
  • 58
  • 91