Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a variable inside a function [duplicate]

Lets say I have an inline script tag that has a very simple code as follows

(function() {
 var test = "This is a simple test";

 function modifyTest(s) {
  s = "Modified test text";
 };

 modifyTest(test);
 console.log(test) //Will still display "This is a simple test"

 })();

However if i use test = modifyTest(test); the change is applied my question is this. Is this the only way to modify a variable in javascript inside a function, meaning i must always do

source = function(source); inorder to alter a variable inside a function,

or am i missing a scope concept that is preventing me from accomplishing this?

like image 893
Mouseroot Avatar asked Feb 24 '14 03:02

Mouseroot


1 Answers

The modifyTest function is essentially creating a local, function-level variable called s; that variable only exists within the scope of the function, so modifying it will not effect external scope.

If you want to modify the external scope, you would not use an argument:

var test = "This is a simple test";
function modifyTest(){
    test = "modified test text";
}
console.log(test);   // This is a simple test
modifyTest();
console.log(test);   // Modified test text

Not that you can modify an object passed by reference, so you can modify something's properties:

var o = { test: 'This is a simple test' };
function modifyTest(x){
    x.test = 'modified test text';
}
modifyTest(o);
console.log(o.test);   // modified test text

You could even pass in the name of the property you wish to modify:

var o = { test: 'This is a simple test' };
function modifyTest(x, name){
    x[name] = 'modified test text';
}
modifyTest(o, 'test');
console.log(o.test);    // modified test text
like image 160
Ethan Brown Avatar answered Oct 15 '22 01:10

Ethan Brown