In JavaScript, a global variable is accessible throughout your entire code, across all functions and scopes. You can declare it:
- Using
var
outside any function: - Without
var
,let
, orconst
(not recommended):
Global variables are attached to the global object (window
in browsers or global
in Node.js), making them prone to accidental overwrites and hard-to-trace bugs.
Best Practice:
Limit global variables by using functions or modules to encapsulate scope and prevent pollution of the global namespace.