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.
Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval() . See Never use eval()!, below. The eval() function evaluates JavaScript code represented as a string and returns its completion value.
In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.
JavaScript functions are essential when writing JavaScript programs if you want to execute a block of code as many times as you want without having to write the same block of code repeatedly in your program. We can simply say the function is a saved algorithm given to a program to work with when called upon.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With