Ask coding questions

← Back to all posts
Why do people say that global variables are bad
dnilem26 (8)

I have always heard that you should not use global variables, but I use them a lot and never encounter any issues. Why are global variables bad and what should I use instead of global variables?

Answered by IntellectualGuy (823) [earned 5 cycles]
View Answer
Comments
hotnewtop
EdwardBentler (35)

@IntellectualGuy , @dnilem26 , and I'd like to know who for ... reasons.

IntellectualGuy (823)

@dnilem26 It's just best practice to use local, and there is a pretty common rule for declaring variables in JavaScript,
const is the best, use it if you can
let is the best, if you want to use a variable, that changes.
var should be only used, when you need the global functionality.

IntellectualGuy (823)

@dnilem26 Can you mark my answer as the correct answer?

Coder100 (18148)

Global variables are bad because if you made a library, and they used global variables, it will conflict with other variables too.

so unless you are making a library, global variables are not truly a bad thing, but it makes it hard for your code to be maintained as it is hard to find where it was defined.

By the way, this is a global variable:

global = 5;

window.global = 5;