shal shal - 1 month ago 5
Javascript Question

Is there a way to tell whether a function parameter was passed as either a literal or as a variable?

I have a function:

function hello(param){ console.log('param is '+param); }


And two calls. First:

hello(123)


Second:

var a=123; hello(a);


Is there any possible way to tell, from within the
hello
function, whether
param
was passed as a
var
or as a literal value?

NOTICE: I am not trying to solve a problem by this. There are many workarounds of course, I merely wanted to create a nice looking logging function. And also wanted to learn the boundaries of JavaScript. I had this idea, because in JavaScript we have strange and unexpected features, like the ability to obtain function parameter names by calling:
function.toString
and parsing the text that is returned.

Answer

No, primitives like numbers are passed by value in Javascript. The value is copied over for the function, and has no ties to the original.

Edit: How about using object wrapper to achieve something like this? I'm not sure what you are trying to do exactly.

You could define an array containing objects that you want to keep track of, and check if its in there already:

var registry = []  // empty registry
function declareThing(thing){  
   var arg = { value: thing }    // wrap parameter in an object (for example an array)
   registry.push(arg)    // register object
   return arg;     //return obj
}
function isRegistered(thingObj){  
   return (registry.indexOf(thingObj) > -1)
}

var a = declareThing(123); 
hello(a);

function hello(param){ 
    console.log(isRegistered(param)); 
}
Comments