LoveAndHappiness
LoveAndHappiness

Reputation: 10135

How to reduce scope to prevent variable from being modified

I have the following variable:

var a = [30,6,26,49,3,9,28];

And the following two functions:

function init(data) {
  var modifiedData = data.reverse().slice(1, data.length).reverse();
  return modifiedData;
}

// Output should be:
// Init: 30,6,26,49,3,9,28
// [30, 6, 26, 49, 3, 9]

function last(data) {
  var modifiedData = data.reverse().slice(0, 1);
  return modifiedData;
}

// Output should be:
// Last: 30,6,26,49,3,9,28
// [28]

If I call each function after the other like this:

init(a);
last(a);

I get the following output from the 2nd function:

Last: 28,9,3,49,26,6,30
[30]

Because apparently the 1st function is applying the reverse() on the data and the 2nd function seems to inherit the reverse() from the first function.

How do I use those two functions successively, while using the same variable as reference?

Upvotes: 0

Views: 126

Answers (3)

carraua
carraua

Reputation: 1528

Try using reverse after slice. Slice clones the array.

var a = [30,6,26,49,3,9,28];

function init(data) {
  document.write("Init: " + data);
  var modifiedData = data.slice(0, data.length - 1);
  document.writeln(" " + modifiedData);
  return modifiedData;
}

// Output should be:
// Init: 30,6,26,49,3,9,28
// [30, 6, 26, 49, 3, 9]

function last(data) {
  document.writeln("Last: " + data);
  var modifiedData = data.slice(data.length - 1, data.length);
  document.writeln(" " + modifiedData);
  return modifiedData;
}

// Output should be:
// Last: 30,6,26,49,3,9,28
// [28]

init(a);
last(a);

Upvotes: 1

nils
nils

Reputation: 27174

Array.prototype.reverse reverses the actual array (before you clone in with .slice()). Forget about the reverses, you can do that with array.slice directly:

var a = [30,6,26,49,3,9,28];

function init(data) {
  console.log("Init: " + data);
  var modifiedData = data.slice(0, -1);
  console.log(modifiedData);
  return modifiedData;
}

// Output should be:
// Init: 30,6,26,49,3,9,28
// [30, 6, 26, 49, 3, 9]

function last(data) {
  console.log("Last: " + data);
  var modifiedData = data.slice(-1);
  console.log(modifiedData);
  return modifiedData;
}

// Output should be:
// Last: 30,6,26,49,3,9,28
// [28]

init(a);
last(a);

When you run it, have a look at the browser console to see the result.

-1 is the same as data.length - 1.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386550

Insert at the first line of function:

data = data.slice(0); // make copy

Upvotes: 1

Related Questions