Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between <input type="hidden"> and global JS variable

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?

like image 509
user3719454 Avatar asked Dec 10 '22 23:12

user3719454


1 Answers

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

like image 108
Parag Bhayani Avatar answered Feb 09 '23 00:02

Parag Bhayani