1

I need function change to change variables and return back to Tst1. I expect to get in console:

5
aaa

but have unchanged ones:

6
bbb

My functions:

function change ( aa,bb )
{
    aa=5;
    bb="aaa";
}

function Tst1() 
{
    aa=6;
    bb="bbb";
    change(aa,bb);

    console.log (aa);
    console.log (bb);
}
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
vico
  • 17,051
  • 45
  • 159
  • 315

4 Answers4

3

One way is to move change() into the function test(). Then it shares the same variables as the calling scope.

'use strict';

function test() {

    function change() {
        aa = 6;
        bb = 76;
    }

    var aa = 5,
        bb = 6;
  
  change();      
  document.write(aa + "   " + bb);
}
test();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

JavaScript is like java in that primitives are never passed by reference but objects are always passed by reference. You need to wrap your data in an object and pass that instead:

function change (aa, bb)
{
    aa.value = 5;
    bb.value = "aaa";
}

function Tst1() 
{
    aa = { value: 6 };
    bb = { value: "bbb" };
    change(aa, bb);

    console.log (aa.value); // outputs 5
    console.log (bb.value); // outputs aaa
}
David Zorychta
  • 13,039
  • 6
  • 45
  • 81
1

or you can play with global variable, but it is not a good practice.

var aa,bb;

function change(){
  aa=6;
  bb=76;
}

function test(){

  aa = 5;
  bb = 6;
  
  change();
  
  console.log(aa + "   " + bb);
}

test();
Shubham
  • 1,755
  • 3
  • 17
  • 33
0

Short answer: NO, you can't pass primitive parameters by reference in JS.
One alternative solution to the presented here is to return the result values as array of items:

 
function change ( aa,bb )
{
    aa=5;
    bb="aaa";
    return [aa, bb];
}

function Tst1() 
{
    aa=6;
    bb="bbb";
    result = change(aa,bb);
    aa = result[0];
    bb = result[1];

    document.writeln(aa);
    document.writeln(bb); 
}

Tst1();
Danield
  • 121,619
  • 37
  • 226
  • 255
d.raev
  • 9,216
  • 8
  • 58
  • 79
  • Useful sometimes, yes. But not when the question is specifically about parameter passing and mutating those parameters. – James Thorpe Nov 19 '15 at 12:10