1

I have this simple function in php and the parameter is a pointer. What is the equivalent of this in JavaScript.

<?php

    function test( &$val )
        {
        echo    $val;
        $val ++;
        }

    $value  = 5;
    test( $value );
    echo    $value
?>

Can be done using an object as parameter?

Thank you.

1
  • There is no equivalent in javascript, but you could use variables in a higher scope as a workaround as noted in the answer by Patrick. Commented Feb 3, 2014 at 19:12

1 Answer 1

3

While primitives like numbers,strings etc cannot be passed by reference, all objects/arrays are. So to do what you want first put your value in an object and then pass it

var container = {
   myvalue:5
};

function changeVal(obj){
   obj.myvalue = 8;
}

console.log(container.myvalue); //prints: 5
changeVal(container);
console.log(container.myvalue); //prints: 8
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Patrick, very useful and an easy way to implement on my project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.