0

Trying to write a function using the spread operator to add an element to an array. Below is the code I wrote which keeps returning AssertionError: expected [ Array(5) ] to deeply equal [ 'foo', 1 ]

var chocolateBars = ["snickers", "hundred grand", "kitkat", "skittles"];

function addElementToBeginningOfArray(candyBars,twix) {
  return ["twix", ...chocolateBars];
}

1 Answers1

0

I think there is a typo in your code? I assume you mean to do this instead:

var chocolateBars = ["snickers", "hundred grand", "kitkat", "skittles"];

function addElementToBeginningOfArray(candyBars,twix) {
  return ["twix", ...candyBars];
}

console.log(addElementToBeginningOfArray(chocolateBars);

edit: it print out: (5) ["twix", "snickers", "hundred grand", "kitkat", "skittles"]

Is that what you expect to see?

edit: made the same typo as the one who ask question. corrected this line: return ["twix", ...candyBars];

And indeed because being pick on typo with down voting my answer, let me elaborate more on this and being helpful. The code indeed won't throw error as the topic owner see because the variable chocolateBars has global scope. it will work. The error is more or less seem to me he/she is running a unit test but somehow expecting only one element in the array but indeed they have five? which is how that code work. it should have 5 elements in chocolateBars. so may be fixing the typo can fix his/her issue as he accidentally change chocolateBars

H L
  • 36
  • 7