What is Scope in JavaScript?
Scope is an important concept to know in order to write code in most of the programming languages, and it plays an important part in choosing which variable keyword you'll want to use.
Scope defines variable availability. In JavaScript, we have two scopes: Global and Local.
1. Global Scope: Variables declared outside any code block or function are known as global variables because they have a global scope, and can be referenced from any function or block.
Note: In a JavaScript document, only one global scope exists. Again, any variable declared outside any function or block is globally scoped:
Example: Suppose you have a script file. Maybe MyScript.js
// Initialized outside of function or block
var Name = "Destiny Idika";
function PrintName() {
console.log(Name);
};
PrintName();
In the example above, name is accessible within the PrintName() function, as it has a global scope. It exists in the context of the application That is, the MyScript.js, and the PrintName() function or any other function can reference it from anywhere within MySript.js!
2. Local Scope: Variables declared within any code block or function are known as local variables, because they have a local scope. They can be referenced only within the code blocks or functions in which they're defined.
Example: Suppose you have a script file. Maybe MyData.js
function PrintData() {
// Initialized within a function or block
var Name = "Destiny Idika";
var Age = 20;
console.log(Name);
};
function PrintAge() {
console.log(Age);
}
PrintAge();
The output / Result of the above example:
How come? Age is defined - but it isn't defined in the scope of the PrintAge() function. As far as the function is concerned - no Age variable exists. It starts by checking whether there's a locally scoped variable. Since there's none, it checks whether there's a globally scoped variable. If not - Age is not defined from the context of PrintAge()!
Let's take a look at how var, let and const depend on the scope, and when each should be used!
The var Keyword in JavaScript
In JavaScript, var is a reserved keyword which is followed by a reference variable name. The name defined after the keyword can then be used as a pointer to the data in-memory.
Using var is the oldest method of variable declaration in JavaScript. Let's declare a variable and initialize it by assigning a value to it using the assignment operator (=):
// Initialized within a function or block
var Name = "Destiny Idika";
Alternatively, you can break this down into two steps - variable declaration (what it is), and variable initialization (assigning a value to it):
// Declaration
var Name;
// Initialization
Name = "Destiny Idika";
Scope of var
When defined within a function - any var is restricted to that function. When defined outside of a function, a var is global:
var firstName = "Destiny";
function checkLastName() {
var lastName = "Idika";
}
From the example above, We have two declarations in the preceding example: firstName is globally scoped because it's defined outside a function, and lastName is locally/function scoped because it's defined within a function that is, ChecklastName() function:
var firstName = "Destiny";
function checkLastName() {
var lastName = "Idika";
console.log(lastName); // "Destiny"
console.log(firstName); // "Idika"
}
checkLastName();
console.log(lastName); // Uncaught ReferenceError: lastName is not defined
The Problem with var
var is not block-scoped. When you declare a variable within a code block, using curly braces ({}), its scope "flows out" of the block! For instance:
var name = "Destiny Idika";
var Male = true;
if (Male) {
var name = "Destiny is a Man";
}
console.log(name);
The name that points to "Destiny Idika" is global, and the name that points to "Destiny Idika is a Man" is defined within a block. However, when we try printing the name, we run into:
Destiny Idika
var is not block-scoped. We may think that we've defined a local var name to point to "Destiny Idika", but what we've done in reality is overwrite the var name that initially pointed to "Destiny Idika".
Declaring variables using the var declarations everywhere in your code can lead to confusion, overwriting of existing global variables and by extension - bugs, just as we saw in the code snippet.
This is where let and const kick in!
The let Keyword in JavaScript
The let declaration was introduced with ES6 and has since become the preferred method for variable declaration. It is regarded as an improvement over var declarations and is block-scoped (variables that can be accessed only in the immediate block), circumventing the main issue that can arise with using var.
Scope of let
A variable defined with the let keyword has a scope limited to the block or function in which it is defined. For example:
let firstName = "John";
let lastName = "Idika";
let someBool = true;
if(someBool){
let firstName = "Destiny";
console.log(firstName);
}
console.log(firstName);
In the above example - the firstName referring to "Destiny" and the firstName referring to "John" don't overlap! The code results in:
The firstName declared within the block SomeBool is limited to the block in scope and the one declared outside the block is available globally. Both instances of firstName are treated as different variable references, since they are of different scopes.
The const Keyword in JavaScript
The const declaration was also introduced with ES6, alongside let, and it is very similar to let. const points to data in memory that holds constant values, as the name implies. const reference variables cannot be reassigned to a different object in memory. For example:
const name = "Destiny";
const name = "Jane";
The Results:
Uncaught SyntaxError: Identifier 'name' has already been declared
Scope of const
The scope of a variable defined with the const keyword, like the scope of let declarations, is limited to the block defined by curly braces (a function or a block). The main distinction is that they cannot be updated or re-declared, implying that the value remains constant within the scope:
const name = "Destiny";
var name = "Emeka";
// Uncaught TypeError: Assignment to constant variable
Good Coding Conventions / Good Practices
So, what does this all mean, and which should you choose, other than the obvious requirements to avoid bugs? This can actually be boiled down to a couple of good practices:
- const is preferred to let, which is preferred to var. Avoid using var.
- let is preferred to const when it's known that the value it points to will change over time.
- const is great for global, and constant values like PI.
- Libraries are typically imported as const.
Written by: DESTINY IDIKA
Reading time:
Published 2 Years Ago On Thursday, March 17, 2022
661 Views