Objects and strings in javascript are passed by reference. (Technically, by reference value, which means reassigning with = , a variable inside a function will not affect a variable outside the function, but this is beyond the point for this question.)
This means that it is not worth passing their functions because a copy is not being made. All that is passed to the function is just a pointer to the source object, and it is efficient.
You also need to understand that your first circuit is not working properly:
var response; $.post(url, function(resp){ response = resp; }) function doSomething() {
due to the time of things, you do not know when to call doSomething() . $.post() as you show that it is asynchronous and therefore you do not know when this is done. The resp value in your code MUST be used from the termination function. You must either use it in the completion function, or call something from the completion function, and pass resp to it (for example, your second example). Only then will you get the right time when this data will be available.
source share