In this section we will learn what the local and global variables are and how to use them in JavaScript.
What is Global Variable in JavaScript?
A variable that is created via the var keyword and is declared outside of any function is called a global variable.
Also a variable that is created via either let or const and is declared outside of any block (including function blocks), is considered as a global variable (AKA identifier) as well.
Note: In JavaScript we can simply put a pair of braces {} somewhere in a program and that is considered as a block. So if we declare a variable via either let or const in such block, it will only be accessible within that block and nowhere else. In the scope section, blocks are explained in greater details.
A global variable is accessible inside any block including function blocks. This means within the body of functions we can set or change the current value of a global variable and the other functions will see this change if they call that variable to get its value.
How to Declare Global Variable in JavaScript?
There’s no difference between the way we declare a global variable than a usual variable!
We can use either var, let or const keywords before the name of the global variable.
But the important part to remember is that we should put the global variable outside of any block.
Note: also if you create a variable without the use of var , let, or const, and put that in the body of a block, the becomes a global variable immediately! That means such variable could be accessed from anywhere in your program. Be aware that such variable must come on the left side of the assignment operator and therefore we should assign a value to it if we want to turn it into a global variable.
For example:
function name(){
name = “John”;
}
Here the name variable is declared without the use of var, const, or let keyword and so it is considered as global variable.
Example: creating global variable in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
let name = "John Doe";
function one(){
name = "Jack";
}
function two(){
name = "Omid";
}
one();
two();
document.querySelector(".output").innerText = name;
</script>
</body>
</html>
Here, there’s a variable named name. The variable is created via the let keyword and because this variable is declared outside of any block, it is considered as a global variable.
In the example, there are two functions as well. Inside the first function one(), we’ve accessed the variable and assigned the value Jack to it. In the second function two() we’ve accessed the global variable name as well and changed the value to Omid.
Now when the one() statement ran, the body of this function is executed and the current value of this global viable name is changed to the value Jack.
After that, the second function two() executes and the value Omid will be set as the current value of the name variable.
At the end in the last statement, we have the document.querySelector(".output").innerText = name;. Here we got the value that is assigned to the name variable and sent it as the content of the <p> element on the page.
As you can see a global variable is accessible inside all blocks and functions.
Example: global variable in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
{
let name = "John Doe";
}
document.querySelector(".output").innerText = name;
</script>
</body>
</html>
In this example there’s a block and a variable named name that is created via the let keyword. So as we explained at the beginning of this section, if a variable is created via the let keyword and inside a block, it is not considered as a global variable.
So here because there’s not a global variable named name in this program; when the execution engine reaches to the document.querySelector(".output").innerText = name; statement, it won’t see a global variable with the name name and for this reason, the final content of the <p> element will be empty.
Example: global variable in JavaScript refactoring the last example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
{
var name = "John Doe";
}
document.querySelector(".output").innerText = name;
</script>
</body>
</html>
If we create a variable inside a block with the keyword `var` but outside of any function just like the example above, it is considered as a global variable.
So in this example the name variable is registered as a global variable, because it is declared with the keyword var and outside of any function even though it is in a block.
For this reason, when the execution engine reaches the document.querySelector(".output").innerText = name; statement, it will check the global environment to see if there’s a variable with the name name and because there’s one, it will use its value as the content of the <p> element.
What is Local Variable in JavaScript?
A variable that is created inside the body of a function using var, let, or const is considered as a local variable.
Note: also a variable that is created via the let keyword in a pair of braces {} outside of any function, is still considered as a local variable.
A local variable is only accessible within the block that is defined. This means if in one function we declare a local variable, it won’t be accessible in another function.
Example: creating local variable in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
function funcOne(){
let name = "Jack";
console.log(name);
}
function funcTwo(){
console.log(name);
}
funcOne();
funcTwo();
document.querySelector(".output").innerText = name;
</script>
</body>
</html>
Output:
Jack
In this example there’s a variable defined in the funcOne() function with the name name.
This variable is accessible in the funcOne() function from the opening brace { to the closing brace } of this function. Basically, this is the boundary of this variable.
But we can’t access this variable in another function such as funcTwo().
So here when we first called the funcOne() function, we could get the value of the name variable and send it to the browser’s console.
But when we called the funcTwo() function, the variable name is completely hidden from this function and so when we attempted to get the value of this variable and send it to the browser’s console in the body of the funcTwo() function, no value actually got printed on the console!
Creating global variables inside blocks and functions:
First of all, in JavaScript we can create a variable without the use of const, let, and var keywords. In a situation like this, the variable is considered as global.
So if we create a variable inside a function or a block but without the const, let and the var keywords, it is considered as a global variable.
Note: again, be aware that the target variable must be declared and initialized at the same time! That means, we need to put the variable on the left side of the assignment operator = and assign a value to it at the same time.
Example: creating global variables inside functions
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
function one(){
name = "Jack";
}
function two(){
name = "Omid";
}
one();
two();
document.querySelector(".output").innerText = name;
</script>
</body>
</html>
Here we have two functions named one and two. But there’s no global variable for now.
The first statement in this example is the call to the one() function.
Inside the body of this function there’s a variable named name and the value Jack is assigned to it. Now if we look at the variable, we can see that there’s no declaration keyword (let, const, var) on the left side of the variable. This means the variable is global.
Note: until the body of the function runs, the variable is unknown to the outside of that function. Only after the execution of the function's body, the variable becomes global.
After the first function one() executed, the second statement which is the two() function will run.
Inside the body of this function again there’s a variable named name with the value Omid is assigned to it. This time because there’s a variable named name already registered in the global (outside of any function), the execution engine will not register a new variable with this name and use the one that is already declared. So the value Omid is stored in the already registered global variable name.
Now in the last statement after the execution of the two() function, we’ve took the value of the global variable name and set it as the content of the <p> element.
Variable Shadowing JavaScript
In JavaScript if we create a function and call a variable in that function to get its value, first the body of the function will be checked to see if the target variable is defined in that function. If yes, the value of the variable that is declared inside the body of the function will be used. This means even if we had a variable with the same name in the global scope, the value of the local variable will be chosen and not the global one.
Basically the search for the target variable starts from the inner most block {} and goes up until it reaches the global space (outside of any block and functions).
Note: in case the target variable is not defined in the global scope either, we would get either a reference error or the value undefined. This part is explained in the scope section.
The way that the JavaScript’s execution engine looks for variables, create an interesting effect which is called variable shadowing.
In its simplest form, variable shadowing means hiding the value of a global variable from being used in a function by creating a local variable with the same name as the global variable in that function.
Example: creating variable shadowing in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<script type="text/javascript">
const fullName = "John Doe";
function funcOne(){
let fullName = "Omid Dehghan";
console.log(fullName);
}
funcOne();
</script>
</body>
</html>
Output:
Omid Dehghan
Here, there’s a global variable named fullName with the value John Doe. Also there’s a function named funcOne(). Inside the body of this function there’s a local variable named fullName with the value Omid Dehghan.
Now inside the body of this function we’ve called the console.log() to send the value of the variable fullName to the browser’s console.
But because the execution engine starts its search for a variable within the inner most block, the local variable fullName is the closest declared variable and so its value will be selected. The global variable in this case is ignored or essentially shadowed.
Example: variable shadow in JavaScript's
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<script type="text/javascript">
const fullName = "John Doe";
function funcOne(){
let fullName = "Omid Dehghan";
{
let fullName = "Jack Bauer";
console.log(fullName);
}
}
funcOne();
</script>
</body>
</html>
Output:
Jack Bauer
Here in the body of the funcOne() function, there’s another block of code that has the variable fullName. Inside this inner block, there’s a call to the browser’s console that takes the value of the variable fullName.
Now because the inner block of the function also has a variable fullName, the value of this variable is the one that will be sent to the browser’s console. So the other two variables with the same name in the function’s body and the global one are ignored.