Javascript: Passing large objects or strings between function considered a bad practice

javascript

Solution

Objects and strings in javascript are passed by reference. (Technically by value of reference, which means reassigning with `=` the variable inside the function won't affect the variable outside the function, but that's besides the point for this question.)

That means that it is not expensive to pass them to functions because no copy is made. All that is passed to the function is just a pointer to the original object and this is efficient.

You need to also realize that your first scheme does not even work properly:

var response;

$.post(url, function(resp){
   response = resp;
})

function doSomething() {
  // do something with the response here
}

because of the timing of things, you don't know when to call `doSomething()`. `$.post()` as you show it is asynchronous and thus you have no idea when it is actually done. The `resp` value in your code MUST be used from the completion function. You must either use it in the completion function or call something from the completion function and pass `resp` to it (like your second example). Only then will you get the timing correct for when that data is available.

Problem

Is it considered a bad practice to pass around a large string or object (lets say from an ajax response) between functions? Would it be beneficial in any way save the response in a variable and keep reusing that variable? So in the code it would be something like this: ``` var response; $.post(url, function(resp){ response = resp; }) function doSomething() { // do something with the response here } ``` vs ``` $.post(url, function(resp){ doSomething(resp); }) function doSomething(resp) { // do something with the resp here } ``` Assume `resp` is a large object or string and it can be passed around between multiple functions.

Original source