What is Wrong with Global Variables in JavaScript?

preview_player
Показать описание
JavaScript makes it easy to create global variables, but we are told that global variables are bad. This video looks at what is wrong with global variables in JavaScript and how to avoid creating them.

For a complete list of all our tutorials:

Рекомендации по теме
Комментарии
Автор

Honest and clear reasoning on global variables.
At times it may seem that global vars are the only way to find the state of some relevant attribute. For example, if you code up your own JavaScript image slideshow. For each of the console function buttons like >| (next), |< (previous), II / > (pause/play), etc you need to know the CURRENT image (or its index) and whether the slideshow is presently cycling or not. That means that if you write a separate JS function for each of these console functions, it must be able to get values for i (current image index), cycling (a boolean) and global functions like load(), change() and cycle().
Of course, it is better and safer to enclose all the previously described global entities within a single global function that returns access to those sub-functions objects actioned when a user clicks on a slideshow console button. So if a user clicks the II / > button (Play/Pause), function SLIDESHOW.play-pause() would be run and if he/she clicked the >| button (Next Slide) function SLIDESHOW.next() would be run, etc.

benzflynn
Автор

I have a question why did this.name run since it is inside a function we did not run and punct did not?

Aimopotis
Автор

If you simply put your globals in an object or reserve a prefix for all global variables (I use an underscore, e.g. var _currentTeam), then there will be no danger of overwriting those unintentionally.

falcon
Автор

ES6 introduced the keywords "let" and "const". What do you think about global variables declared using let and const?

naeemhaq
Автор

So what if I use CONST global variables, surely they won't clash with other variables and an error will be reported should an attempt to use the same variable name twice occur?

veehope
Автор

Good. you videos are unique as compared to others and very helpful.

aqibfayyaz
visit shbcf.ru