JavaScript Variable scope with Examples

Hello there welcome to today’s article. Today we are going to talk about scopes of variables in JavaScript, what they are with some examples.

Knowing the scope of variables determines how we can access them in our programs. This is because Variables can’t be accessed outside their scope.

There are 4 types of scopes in JavaScript and we are going to talk about them with examples.

What you should expect in this article, includes:

Outline

1) What is variable scope

2) Types of scope In JavaScript with example

3) Conclusion

What is variable scope

Scope is an important concept to discuss when it comes to declaration and accessibility of variables and their values.

The scope of a variable can define a variable to be either a global or a local variable, which also gives a definition of how the variable can be accessed.

If you want to code in JavaScript, you must understand the concept of scope. Let’s try an experiment that will give a basic foundation of what I am talking about.

Let’s say you have a variable “msg” declared, and you want to access it using the console you can simply do this:

let msg = "Hello, I love You"

console.log(msg)

Fine, the “msg” variable is accessible and the code will print out “Hello, I love you” in the console. But what if you declared the “msg” variable inside an if condition block like this:

let name = "Mary"

if (name =="Mary") {

    let msg = "Hello, I love You"

}

If you should try accessing the “msg” variable outside the if block like this:

let name = "Mary"

if (name =="Mary") {

    let msg = "Hello, I love You"

 }

console.log(msg)

This will give a reference error, saying “msg” is not defined. This is because variables declared inside a conditional block or any other block of code is local to the block and can only be accessed inside the block.

So, if you want to access the “msg” variable this time you have to do so inside the if block like this:

let name = "Mary"

if (name =="Mary") {

    let msg = "Hello, I love You"

    console.log(msg)

}

Locally scoped variables such as variables declared inside conditional statement can only be accessed inside the block. Don’t worry we will discuss about the different types of scopes in JavaScript shortly.

Types Of Scope In JavaScript

Like I said earlier in this article we have 4 major types of scopes in JavaScript:

i) Block Scope

ii) Function scope

iii) Global scope

iv) Lexical scope

Block scope

Prior to ES6, declaration of variable was done using the var keyword alone, which could only have global or function scope. But in ES6 we now have “let” and “const” keywords for declaration of variables, which leads us to the topic of discussion “block scoped variable”.

Variables declared inside a block with the “let” and “const” keyword have a block scope.

Block scoped variables are local to the block in which they were declared, so cannot be accessed from outside the block that they were declared in.

Example:

{
    let msg = "Hello, I love You"
}

Console.log(msg)

Doing something like the above example will result to an error on the console. This is because the variable “msg” was declared inside the {} block making it local to the block. This explains why we could not access the “msg” variable from our previous example. Block scope applies to variables declared inside conditional blocks and loops.

To access variable declared inside a block like the one we just declared, we need to do so inside the block. Like this:

{

    let msg = "Hello, I love You"

    console.log(msg)

}

Note that if you declare a variable inside a block, it is possible to still declare and use another variable with the same name outside the block.

Example:

{
    let msg = "Hello, I love You"
    console.log(msg)
}

let msg = "This is not a block scope"
console.log(msg)

Notice that on the console you have both “Hello I love You” and “This not a block scope”. This is because one is not a block variable and the other is and outside a block a block scoped variable is not recognized.

Also remember I said variables declared inside a block with the const and let key word have a block scope, so what about the ones declared with the var keyword.

Well declaring a variable inside a block with the “var” keyword does not give it a block scope. In fact, you can access variables declared with var keywords outside their blocks.

Example:

{
    var msg = "Hello, I love You"

}

Console.log(msg)

The above example will run perfectly well and you should see, “Hello I love you” in the console.

Function scope:

Just like the block scope variables, variables declared inside a function are local to the function and cannot be accessed from outside the function, but the only difference between a function scope and a block scope is that, both variables declared with the “var” keyword have a function scope

Example:

function greetings() {

    var msg = "Hello, world"

}
function myMessage() {

    let msg = "You are online"

}
function reply() {

    const msg = "It’s Amazing"

}

The variable “msg” is local to the functions, “greetings”, “myMessage” and “reply” and so it can’t be accessed outside the block of these functions.

Example:

function greetings(){

    var msg = "Hello, world"

}

Console.log(msg)

The code above will not run, it will produce an error although the variable was declared using the “var” keyword.

The same thing will apply to variables declared with “const” and “let” keywords. So, in order to access the “msg” from any of the functions above, we have to do so inside the function block just like the block scope. So, you will do something like this:

function greetings(){

    var msg = "Hello, world"

     console.log(msg)

}

Or

function reply() {

    const msg = "It’s Amazing"

    console.log(msg)

}

And

function myMessage() {

    let msg = "You are online"

    console.log(msg)

}

Also note that since function scoped variables and block scope variable behave similarly, you can also declare a variable inside the function block and declare another variable with the same name outside the function just like the block scope.

Global Scope

A variable declared outside a block or a function automatically have a global scope and can be accessed from anywhere inside the code.

Example:

const age = 17

function myMessage() {

    console.log(age)

let msg = "You are online"

}

console.log(myMessage())

If you run the above code, you will have the value of age printed out in the console, even though you tried accessing it inside the function block. The same thing applies to variables declared outside the block or function with the “var” and “let” keywords.

Also note that assigning a value to a variable that has not been declared, makes it an automatic global variable, even though you do so inside a function.

Example:

myMessage();

console.log(age)

function myMessage() {

    age = 17

}

console.log(age)

the above code will print out 17 twice in the console, even though age was not declared before and you tried accessing “age” from outside the function block.

In JavaScript the global scope is the entire JavaScript environment. That is code inside and outside the block belong to the global scope. So, this explains the reason why variables declared outside a block can be accessed from inside a block or anywhere else in the program.

Lexical scope:

Finally, we have the lexical scope of functions, where inner functions in a nested group of functions have access to the variables and other resources declared inside their parent function

Example:

function parentFunc(){
    let greetings ="Hello from here"
    function childFunc(){
        console.log(greetings);
    }
    return childFunc();
}
const inner = parentFunc()
console.log(inner)

From the above example, we defined a function with a variable called “greeting”. Now inside that function we also defined another function and tried accessing the “greetings” variable, which was positive after calling the “parentFunction” which was assigned into the inner variable.

So, a function that is defined inside another function has access to the variable declared inside their parent function just as you have seen earlier, this is because the inner functions are lexically bound to their parent functions.

In order to understand the concept of JavaScript scope properly, you need to have a clear knowledge of what is called a scope chain. A scope chain is a kind of hierarchy, from the parent scope, till the global scope is reached.

For example, when a variable is declared, JavaScript looks down the scope chain from the parent scope, to find the requested variable, if the requested variable is not in the parent scope, it looks till it gets to the global scope. If the requested variable is not in the global scope, then it throws a reference error.

Conclusion

JavaScript scope is a very important topic to discuss. In order to code in JavaScript, you must know and understand the concept of scope as this will help you in knowing how to declare a variable and how to access them.

In some tutorials or articles you might have seen or heard them make mention of only two types of scope (ie local and global scope) well to some point this is not all so correct, because the different keywords “let”, “var” and “const” behave differently when it comes to scope.

For example, even though block scoped variables are not meant to be accessed outside a block of code, variable declared with the “var” keyword violates this rule, this is why we have to divide global scope and local scope into more specific groups.

So, in this article, we discussed about, the various types of scope in JavaScript and how variables can be declared and access in each of them. We also talked about Lexical scope, where functions inside a function can access variables inside their parent functions.

I hope you enjoyed the content of this article, please remember to like, share to your friends and comment, see you next time.