In our codebase we have both of them and I don't understand when to use which...
In case of <input type="hidden" id="someFlag" />
we write/read value in the following way $("#someFlag").val('1');
and $("#someFlag").val() == '1'
Why not just simply add global variable into the JavaScript file?
var someFlag2;
...
someFlag2 = '1';
someFlag2 == '1'
Are there some differences between these approaches?
As you are using AJAX request I want to guide you, You should avoid both approaches if possible First, Global variables why you should avoid global variable is mentioned in below reason...
The reason why global variables are discouraged in javascript is because, in javascript all code share a single global namespace, also javascript has implied global variables ie. variables which are not explicitly declared in local scope are automatically added to global namespace. Relying too much on global variables can result in collisions between various scripts on the same page
To know how to avoid global variables, this will be helpful -> How to avoid global variables in JavaScript?
Sameway hiddenfields adds extra fields on dom and getting values from DOM elements in heavy process, and similarly you will get values only in text formats, so you always need to convert it to interger or objects from JSON, which again will be overhead
I would prefer to save it in some closures where it is necessary, If you want to know how you can apply this in your current scenario we can talk here in comments.. For information on closure you can have a look at this stackoverflow question
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