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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With