Is it possible to pass variables by reference in javascript? [duplicate]

1

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

Example:

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

$y = 2;

fn($y);

echo $y; // Imprime 10

And in the javascript? Is there any way to do something similar?

    
asked by anonymous 02.10.2015 / 17:49

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 passed parameter.

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

var obj = { x: 2 };
alteraX(obj);
console.log(obj.x);
    
02.10.2015 / 17:52