2

my question is as simple as this: How can I pass parameters as reference or as value in JavaScript as I could do in PHP.

Example with PHP:

    function increase(&$value){ 
        $value++;
        return $value; 
    }
    $number = 4;
    echo increase($number) . "<br/>";
    echo $number;

How can I accomplish something similar with JavaScript?

Thank you and Blessings.

3
  • 1
    See codekoel.com/pass-by-value-and-pass-by-reference-in-java-script TLDR; Values cannot be passed-by-reference. Objects are always passed by reference Commented Sep 15, 2020 at 19:08
  • @rickdenhaan, that's a better duplicate link than mine IMO Commented Sep 15, 2020 at 19:10
  • 1
    Thank you @reed your comment has answered my question. Commented Sep 15, 2020 at 19:19

1 Answer 1

0

Assign the return value to a variable.

const nextNumber = increase(number);
console.log(nextNumber);

where increase does the same thing as your PHP function:

function increase($value){ 
    $value++;
    return $value; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's the same as in @ReynaldRamirez's code. Increment a variable and return it.
Your code doesn't work the same as in PHP. If you will run increase multiple times in JS it will always return the same value, but in PHP it will increase value every time. So in JS if you will pass 4 it will return always 5, but in PHP it will return 5, 6, 7, etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.