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

Is it bad practice to pass a large string or object (say from an ajax answer) between functions? Would it be useful to somehow store the response in a variable and continue reusing this variable?

So, in code, it will 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 } 

Suppose resp is a large object or string, and it can be passed between several functions.

+6
source share
1 answer

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() { // do something with the response here } 

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.

+10
source

Source: https://habr.com/ru/post/970052/


All Articles