Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 384
shal Avatar asked Oct 06 '16 14:10

shal


People also ask

How can you get the type of arguments passed to a function?

There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.

Are parameters passed by reference in JavaScript?

In JavaScript array and Object follows pass by reference property. In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value.

Which of these data types in JavaScript when passed as function arguments are passed by reference?

So, Primitive values like number, string, boolean are passed by value while Objects and arrays are passed by reference like above said.


1 Answers

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 an 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:

var registry = []  // empty registry
function declareThing(thing){  
   var arg = { value: thing }    // wrap parameter in an object 
   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)); 
}
like image 170
santi-elus Avatar answered Oct 25 '22 04:10

santi-elus