function swap(a,b){
let temp = a;
a = b;
b = temp;
}
let abc = [2,3];
swap(abc[0],abc[1]);
console.log(abc); // [2,3]
Can anyone explain why for me please?
function swap(a,b){
let temp = a;
a = b;
b = temp;
}
let abc = [2,3];
swap(abc[0],abc[1]);
console.log(abc); // [2,3]
Can anyone explain why for me please?
Those arguments you are passing into the function are local only to the function. So yes, a
and b
get swapped inside the function but once the function is done those variables basically disappear.
Now, if you passed an array with two items into the function then you could swap the elements in the array and it would persist outside of the function because when you pass an object into a function you are working with that actual object inside of the function.
but as a = b, then I pass “abc[0]” into parameter “a”, then “abc[1]” into “b”, doesn’t it means abc[0]=abc[1]? Can you explain more about this pkease? thanks!
What do you expect this code to do?
function testThis(a) {
a = 42;
}
let myVar = 2;
testThis(myVar);
console.log(myVar);
And this one
function testThis(a) {
a[0] = 42;
}
let myVar = [1, 2, 3];
testThis(myVar);
console.log(myVar);
yeah, that is quite frustrating for me. So how can I create a function that change a variable value?
Did you run both pieces of code? What did you see?
You change things outside of a function by passing in an object or array or by using the return value. Scope works like this on purpose. You don’t want local variables polluting or disrupting the global space without you explicitly saying that they should.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.