Variable Scope

Variables in JavaScript can have local or global scope. The scope of a variable refers to the variable's visibility within a script. Variables accessible to a restricted part of a script are said be local. Variables that are accessible from anywhere, are said to be global.

Global variables can be created anywhere in JavaScript code, simply by assigning initial values to them. Once created, global variables can be accessed from any part of the script and retain their values until the script ends.

In JavaScript, newly created variables are assumed to be global, regardless of where they are created, unless explicitly defined with the var keyword.

Important:

Ambiguity can arise when a global variable and local variable have the same names. JavaScript resolves this ambiguity by giving priority to local variables.