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)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.