Dawid S Dawid S - 1 month ago 22
Javascript Question

slice dosent work in function js

Simple thing doing eloquentJS exercise. Slice doesn't return right output from array in functions parameter

console.log(swapArray([1, 2, 3, 4, 5, 6, 7]));

function swapArray(insertTab) {
console.log([0, 1, 2, 3, 4].slice(2, 4)); // this work fine
insertTab.slice(2, 4); // this does nothing
return insertTab;
}

Answer

Array.prototype.slice() doesn't mutate the array it is called on, but returns a new array. Assign this return value to insertTab and it works fine:

console.log(swapArray([1, 2, 3, 4, 5, 6, 7]));

function swapArray(insertTab) {
  console.log([0, 1, 2, 3, 4].slice(2, 4));
  insertTab = insertTab.slice(2, 4);
  return insertTab;
}