0

Is there a way in javascript to send a var by reference and initialize it inside a function.

For ex:

function init(param){param = function(){}}
var undefinedVar;
init(undefinedVar);

undefined var will remain undefined after this invocation.

I know that only objects are sent across functions as reference for ex:

function init(param){param.attr='';}
var objectVar = {}
init(objectVar);

After this the value of objectVar will be {attr:""}

Anyone know a way to force this behaviour for non-object variables?

Thanks

Javier Abrego
  • 462
  • 3
  • 12

2 Answers2

0

Only primitive types (string, boolean, number, null, undefined) are passed by value in JavaScript. But array and object are passed by reference.

With an array :

function init(param){param.push('hello')}
var undefinedVar =[];
init(undefinedVar);
console.log(undefinedVar); // print ['hello']

With an object :

function init(param){param['test'] = 'init'}
var undefinedVar = {};
init(undefinedVar);
console.log(undefinedVar); // print {test : 'init'}

They are some posts which talk about it :

Javascript by reference vs. by value

Hope it helps.

Flament Mickaël
  • 354
  • 2
  • 10
  • That's exactly what I mentioned in my question "I know that only objects are sent across functions as reference for ex:...", Array or Arguments is just another kind of object in JS – Javier Abrego Feb 07 '18 at 15:25
0

The most "similar" way of simulating the send by reference way that I found is accessing the context of the parent scope sending the reference of the var name as a string:

var undefinedVar, undefinedVar2, undefinedVar3;

function init() {
  for(var i=0; i<arguments.length; i++){
    this[arguments[i]] = new Function();
  }
}
init('undefinedVar', 'undefinedVar2', 'undefinedVar3');

This can be useful for example initializing or validating arguments inside a function.

For example instead of having to repeat code like this

(function myContext(arg1, arg2, arg3){
  if(!arg1 || (typeof(arg1)!='function')){
    arg1 = new Function();
  }
  if(!arg2 || (typeof(arg1)!='function')){
    arg2 = new Function();
  }
  if(!arg3 || (typeof(arg1)!='function')){
    arg3 = new Function();
  }
  console.log(arguments);  
})()

we could do the following

function init(context) {
  for(var i=1; i<arguments.length; i++){
    if(!context[arguments[i]] || (typeof(arg1)!='function'))
      (context[arguments[i]] = new Function());
  }
}

(function myContext(arg1, arg2, arg3){
  init(arguments, 'arg1', 'arg2', 'arg3');
  console.log(arguments);  
})()

This prints

arg1:ƒ anonymous() arg2:ƒ anonymous() arg3:ƒ anonymous()

This helps to avoid duplicity of code in this kind of situations.

Javier Abrego
  • 462
  • 3
  • 12