Reputation: 422
I have a doubt, I'm creating some applications in javascript, but not if I'm doing the right to declare global variables for example:
var aux;
and then use these as the cache on all my functions:
function something (data) {
aux = 2 * data;
return aux;
}
something2 function () {
aux = something (5);
}
something3 function () {
aux = "something else";
}
I do something like this declare the variable "aux" and use it as a cache in many places, but this is good ?, or do I need to create separate variables for each function where use?
Upvotes: 0
Views: 2978
Reputation: 6221
Generally speaking, you do not want to "contaminate the global namespace". It hinders performance, and can also lead to problems later (like if that variable name is reused).
Think about how you could rewrite your code to not use global variables. Usually there is a way around it. Also you should familiarize yourself with the concept of the IIFE - http://en.wikipedia.org/wiki/Immediately-invoked_function_expression
It's
return aux
though you could just do
return aux = 2 * data
or if you don't need to store the value in aux you could just
return 2 * data
Upvotes: 2