4

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?

user3719454
  • 994
  • 1
  • 9
  • 24

4 Answers4

6

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

Community
  • 1
  • 1
Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52
3

See type="hidden" input is a better choice if you want to post some important values to server, which you do not want to show to the user. Typically people use it when working with forms without ajax, And if you are working with forms then you have to give an attribute name="" to it because this is the attribute which is send to the server as a key.

While global variables in js is useful in someway but i guess it is not recommended because it makes the code a bit unmaintainable.

Jai
  • 74,255
  • 12
  • 74
  • 103
2

One difference in my thoughts is.

While posting a form you will be able to get the value of hidden fields as part of request variable how ever in case of global javascript variable you need to send it explicitly in the POST or GET call.

If you need variable only for client side than you can use any of them but if you need send them with server call in that case input type="hidden" would be a good choice

Vivek Gupta
  • 955
  • 4
  • 7
2

Hidden fields can be useful for data structure consistency.

Sending 4 "real" form fields plus two hidden fields is more easily comprehensible than sending 4 real fields plus two globals, even if you're 100% AJAX.

Roger Krueger
  • 283
  • 3
  • 8