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']

3

1 Answer 1

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...).

Sign up to request clarification or add additional context in comments.

1 Comment

Or just accept the array as an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.