Is it possible to pass variables by reference in javascript?

Asked

Viewed 3,089 times

2

In PHP it is possible to pass variables by reference when we flag the parameter name with a & before. And thus, the variable can be changed without the need to reallocate value.

Example:

function fn(&$x) {
    $x *= 5;
}

$y = 2;

fn($y);

echo $y; // Imprime 10

What about javascript? Is there any way to do something like this?

1 answer

0

Not directly. But you can use an abstraction, such as an array or an object, for example, so that a function can "change the value" of the parameter passed.

function alteraX(obj) {
    obj.x *= 5;
}

var obj = { x: 2 };
alteraX(obj);
console.log(obj.x);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.