The scope of a variable in JavaScript can either be a function or a block, depending on how the variable is declared.
Variables using the term var
in their declarations have function scope. This implies that they are reachable from anywhere within the defined function, including any nested functions. Function-scoped variables are not constrained to the block in which they are defined.
function myFunction() {var x = 10; // Function-scoped variableif (true) {var y = 20; // Function-scoped variableconsole.log(x); // Accessible within the function}console.log(y); // Accessible within the function}myFunction();
Both the x
and y
variables are available throughout the myFunction()
in the example above.
It applies to variables that were declared using the let
or const
keywords. The block in which they are defined, such as a loop (for
, while
, etc.), a conditional statement (if
, switch
, etc.), or a block statement (...)
, is where they can only be used.
function myFunction() {let x = 10; // Block-scoped variableif (true) {let y = 20; // Block-scoped variableconsole.log(x); // Accessible within the block}console.log(y); // Throws an error, y is not accessible here}myFunction();
In this example, x
can be accessed both inside and outside of the if
block, while y
can only be accessed from within the if
block.
It is often advised to utilize block-scoped variables introduced using let
and const
in place of var
for more predictable code behavior because they offer more control over variable scope.
It’s necessary to remember that global variables (i.e., outside of any function or block) are available across the whole JavaScript program. The use of global variables should be kept to a minimum to prevent naming conflicts and unexpected outcomes.
Free Resources