Function Scope can be defined as the boundary of the function denoted by it’s curly braces { }. That means, any code written inside those curly braces are inside the scope of the function. This is where Local and Global variables are introduced in JavaScript.
Make sure to check out our JavaScript Functions lesson for more details on functions in JavaScript
Local Variables in JavaScript 🏠
Local Variables in a function are those variables defined inside the curly braces { } of that function. Which means, that local variables are defined inside the function scope.
Therefore, local variables cannot be accessed outside the function where it is defined 🚫.
Example
function whatIsYourAge() {
var age = 18;
// The variable "age" can be accessed here as it is defined inside the function's curly braces "{ }".
console.log('You are ' + age + ' years old.');
}
whatIsYourAge();
// The variable "age" cannot be accessed here. This will give error.
console.log(age);
NOTE: Anything defined inside the function’s curly braces { } cannot be used outside of that function.
Global Variables in JavaScript 🌎
Global Variables are those variables that are defined outside of any function. Therefore, they can be easily accessed anywhere in our code, even inside any of the functions that we create.
They are the variables defined globally and can be accessed anywhere in our code and also by any of the functions defined ✅. So, global variables are said to have Global Scope.
Example
var age = 18;
function whatIsYourAge() {
// The variable "age" can be accessed here.
console.log('You are ' + age + ' years old.');
}
whatIsYourAge();
// The variable "age" can also be accessed here.
console.log("Hey, I'm " + age + " years old now!");
Output
You are 18 years old.
Hey, I'm 18 years old now!
You write Local Variables when you want some variables that are specific to that certain function only whereas you write Global Variables when you want some variables that can be used by any function and also anywhere in your code.
In this way, variables can be used as Local or Global in a function in JavaScript.