0

I see my global variable which is an object is getting modified inside a function.

Below is the example I created:

var globalVarForTest = ["dfbsdfbsdfb", "sfgb", "gtsgt", "ttt"];

function testingError() {

  console.log("BEFORE")
  console.log(globalVarForTest);
  for (var i = 0; i < globalVarForTest.length; i++) {
    console.log(globalVarForTest[i]);
  }


  //Modifying Local Variable
  var localVarforTest = globalVarForTest;
  for (var i = 0; i < localVarforTest.length; i++) {
    localVarforTest[i] = localVarforTest[i].length;
  }




  console.log("AFTER")
  console.log(globalVarForTest);
  for (var i = 0; i < globalVarForTest.length; i++) {
    console.log(globalVarForTest[i]);
  }

}

testingError();

The function prints BEFORE and AFTER different values for a global variable.

How to set a local variable inside a function equal to a global array so that the global array is not modified in the function?

0

2 Answers 2

1

You would have to clone it without reference.

var globalVarForTest = ["dfbsdfbsdfb","sfgb","gtsgt","ttt"];

var temp = globalVarForTest.slice(0);

console.log(temp);
temp.push('temp');
console.log(temp);
console.log(globalVarForTest);

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

Comments

0

you can use JSON native parse method to convert from and to obj..

var globalVarForTest = ["dfbsdfbsdfb","sfgb","gtsgt","ttt"];

            function testingError(){

            console.log("BEFORE")
            console.log( globalVarForTest );
            for( var i=0; i<globalVarForTest.length; i++ ){
                    console.log( globalVarForTest[i]);
            }


              //Modifying Local Variable
            var localVarforTest = JSON.parse(JSON.stringify( globalVarForTest ));
            console.log( localVarforTest );
            for( var i=0; i< localVarforTest.length; i++ ){
                    console.log( localVarforTest[i]);
            }


            console.log("AFTER");
            console.log( globalVarForTest );
            for( var i=0; i<globalVarForTest.length; i++ ){
                    console.log( globalVarForTest[i]);
            }


            }

testingError();

Comments

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.