Reputation: 2018
Is it possible to change the variable value with function like example below? Whenever I change the passed parameter value the original value doesn't change. Why is this happening?
let b = 3;
function t(n) {
n = 5;
}
t(b)
console.log(b) // still 3
I know this can be done like this, but I am wondering why the example above wont work.
let b = 3;
function t() {
return 5;
}
b = t();
console.log(b)
Upvotes: 0
Views: 46
Reputation: 43479
Passing scalar values to function will pass them by value, not by reference.
One solution would be to pass it as object:
let b = {value: 3};
function t(n) {
n.value = 5;
}
t(b);
console.log(b.value);
Upvotes: 2