Local and Global Variable Scope in JavaScript
There are two main types of variable scope in JavaScript; local and global. Local variables are only available inside the function in which they are declared and global variables are available anywhere.
In this tutorial, we will learn how to work with local and global JavaScript variables.
Local Variables
If we declare a variable using var
inside a function it will only be available in that function, in other words, it has a local scope. Let's make a function containing a local variable and check what the variable is outside and inside the function using typeof()
.
function getFruits() {
var fruit = ['apple','strawberry','apricot'];
console.log(typeof(fruit));
}
getFruits();
console.log(typeof(fruit));
object
undefined
The fruit
variable is defined as an object inside the getFruits()
function but outside it is undefined
.
let Variables
let
is also a type of local variable introduced in ES2015 read more about the difference between let and var in JavaScript.
Global Variables
A variable has a global scope and available anywhere in the window
object after its declaration when defined outside of a function.
var fruit = ['apple','strawberry','apricot'];
function getFruits() {
console.log(typeof(fruit));
}
getFruits();
console.log(typeof(fruit));
object
object
Define a Global Variable from Inside a Function
To make a global variable from inside a function, give it a value without putting var
in front of it.
function getFruits() {
fruit = ['apple','strawberry','apricot'];
console.log(typeof(fruit));
}
getFruits();
console.log(typeof(fruit));
object
object
note - make sure you are not unintentionally overwriting the value of other variables when doing the above. This is more likely when using common words as variable names.
Conclusion
You now know the difference between global and local variables in JavaScript and how to make a global variable from within a function. Local variables help ensure you are working with the correct value if there is a large amount of a JavaScript code running.