Javascript Variable Scope in 2.6 Minutes…
Welcome back to the coding apprentice newsletter to returning and new subcribers. Go ahead and comment or reply to me about the content. Spreading the word about the newsletter goes a long way :)
Last week I wrote a piece differentiating javascript variables behaviour when it comes to redeclaring and reassigning. This week I want dig a little deeper and unpick the differences in scope when it comes to variable declaration.
What is Scope?
Where and how variables are declared in Javascript will define their scope. Differences in scope mean differences in accessibility and usability for the variables that we declare. A combination of our choice between the use of variable keywords (var, let, const) with the chosen location of our variable declaration (outside or inside a function…inside of a for loop..) will have an impact on the scope of variables.
Global Scope
Any variable (var, let or const) declared outside of functions or any block of code (not within curly brackets { }) is global scope. Global scope variables can be accessed in any region of our code, inside or outside of functions / code blocks.
var globalVar = 'I am global var';
let globalLet = 'I am global let';
const globalConst = 'I am global const';
function exampleFunction() {
console.log(globalVar, globalLet, globalConst); // Can access global scope variables here
}
exampleFunction(); // Output: "I am global var / I am global let / I am global const"
console.log(globalVar, globalLet, globalConst); // Output: "I am global var / I am global let / I am global const"
Global scope variables can be accessed from anywhere no matter which keyword they were defined with. Globally declared variables must be declared mindfully, with the possibility of maintainability issues arising due to the their potential for naming conflicts.
As mentioned in my previous post, the var keyword is an outdated form of variable declaration. Modern practice requires the use of let and const keywords which in turn will improve the readability of our code by allowing other programmers to identify whether our declared variables are intended to change. It is advisable to always apply “const” unless we know that our variables are going to be reassigned, in which case we should apply “let”.
Block Scope
“let” and “const” variables declared inside blocks of code are block scope. Blocks of code are any lines of code written between curly brackets ( { } ) such as functions, if / else statements and for loops. Block scope variables can only be accessed from within the scope they were declared, attempting to access these block scope variables outside of this will return an error.
function blockScopeFunction() {
if (true) {
const blockConst = 'I am a block-scoped variable with const';
}
console.log(blockConst);
}
blockScopeFunction();
// blockConst is not defined
In the above example an error ‘blockConst is not defined’ is flagged as the variable is attempted to be accessed outside of the scope it was declared. If we move the position of our attempted access to the block the variable was declared in, we will gain access.
function blockScopeFunction() {
if (true) {
const blockConst = 'I am a block-scoped variable with const';
console.log(blockConst);
}
}
blockScopeFunction();
// I am a block-scoped variable with const
Block scope variables can be accessed from a code block created within the code block that the variable was declared in. The following snippet is an example of access to a block scope variable variable from a child code block, as the parent code block is the block in which the variable was declared.
function blockScopeFunction() {
if (true) {
const blockLet = 'I am a block-scoped variable with let';
for (let i = 0; i < 1; i++) {
console.log(blockLet)
}
}
};
blockScopeFunction();
// I am a block-scoped variable with let.
As long as we access a block scope variable from the code block the variable was declared, or a child code block of this, we will not receive an error message.
Function Scope
Only var variables have function scope and as aforementioned, declaring variables with var is outdated and does not adhere to modern practices. Function scope variables have their own scope when declared within a function, meaning they have less narrow accessibility than block scope.
function blockScopeFunction() {
if (true) {
var blockVar = 'I am a block-scoped variable with const';
}
console.log(blockVar);
}
blockScopeFunction();
// I am a block-scoped variable with const
As the above “blockVar” variable has been declared with “var”, we can access the variable outside of the code block it has been declared. We declare and access the variable within the same function allowing us access the variable.
It is essential to understand variable scope to avoid unintended behavior and bugs in your JavaScript code. Using block-scoped variables (with let
and const
) and minimizing the use of global variables can help maintain a clear and predictable code structure.