How to prevent function modifies global variable?

Asked

Viewed 110 times

1

Creating a function to return a given value, from received parameters, it modifies the variable it receives.

For example:

var a = ["oi", "tchau"];

function duplicar(c) {
  var b = c;
  b[0] = b[0] + b[0];
  b[1] = b[1] + b[1];
  b = b.join(" ")
  return b
}
console.log('Variável antes da função: "' + a + '"')
console.log('Retorno da função: "' + duplicar(a) + '"')
console.log('Variável após função: "' + a + '" (não quero que isso aconteça)')

That’s not the function I created in my code, but the same thing is happening. I am quite beginner in Javascript, I do not know why this occurs nor how to prevent.

I want the function to return a value, modifying the variable to only within it, without modifying the variable a in the source scope.

I’ve tried using Let, const, objects...

  • The problem is probably why you did not declare the variable B within the function. Thus, the parameter she is receiving is A, and sub-variable b by a. It was clear?

2 answers

2

The C parameter was receiving array A, and was overwriting it.

var a = ["oi","tchau"];
function duplicar(c){
var x = Array();
x[0] = c[0]+c[0];
x[1] = c[1]+c[1];
return x;
} 

I hope I’ve helped

0

You can use the method .Slice(0) which will create a new array from the first without changing the first:

var a = ["oi","tchau"];
function duplicar(c){
   var b = c.slice(0);
   b[0] = b[0]+b[0];
   b[1] = b[1]+b[1];
   b = b.join(" ")
   return b
}
console.log('Variável antes da função: "'+a+'"')
console.log('Retorno da função: "'+duplicar(a)+'"')
console.log('Variável após função: "'+a+'" (array inalterada)')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.