Is it possible to change the value of the function parameter?
You cannot change the value of an integer or a string in JavaScript BUT you can change the value of the attributes of an object for example
function change(x) {
x.x = 2;
}
let y = { x: 1 };
console.log('Original:', y);
change(y); // will make y.x = 2;
console.log('Modified:',y);
You cannot pass explicitly by reference in JavaScript; however if b
were an object, and in your function you modified b
's property, the change will be reflected in the calling scope.
If you need to do this with primitives you need to return the new value:
function increaseB(b) {
// Or in one line, return b + 1;
var c = b + 1;
return c;
}
var b = 3;
console.log('Original:', b);
b = increaseB(b); // 4
console.log('Modified:', b);