Lesson 7: Scope
What is a Scope?
Scope determines the visibility and accessibility to variables. The concept of scope is used in many different programming languages such as Java, C#, JavaScript and PHP.
Global Scope?
- Global scope variables can be accessed anywhere.
- A global scope variable is variable that is defined outside of functions /conditions.
Example:
var my_name = "Kevin" //Global scope Defined
console.log(my_name); //Output - Kevin
function getName(){
console.log(my_name); //my_name is still accessible
}
getName(); //Output – Kevin
Kevin
Local Scope & Function Scope
- Local variables are accessible only within a function.
- When a variable is defined inside a function it is known as a local variable.
- Once a variable is declared inside a function, it can’t be accessed outside the function.
- Use the var keyword to define a variable for function scope.
Example:
var my_name = "Kevin" //Global scope Defined
function myAge(){
var age = 21; // Local/Function variable defined
console.log ("My age is : " + age);
}
myAge(); //Output will be 21 as the variable is declared inside the function
console.log(age) //Output will be defined as the variable is visible only to the ‘myAge’ function.
console.log(my_name) //Output will be Kevin as it’s a global variable and can be accessed from anywhere.
Kevin
Block Scope
- Block scope is the area of code inside curly brackets . Block scopes are commonly found within if statements, switch conditions and loops such as for or while.
- Block scope variables are defined using the const and let keywords.
- The variables declared inside the brackets are only visible inside the brackets.
Example:
function aboutMe (){
if(true) {
var myName = "Kevin" // Defined function scope
let myAge = 21; //Defined block scope
const favouriteColor = "blue"; //Defined block scope
}
console.log(myName);
console.log(myAge); // Should be defined in the above brackets
console.log(favouriteColor); // Should be defined in the above brackets
}
aboutMe();
//Result of function
// Kevin
// error -as myAge is undefined
// error -as favouriteColor is undefined
If the console.log () for myAge and favouriteColor were defined inside their own braces, it would work.
Reason why it is better to use let than var.
- It’s better to use let than var as let reduces the scope, which essentially makes variables less accessible/visible.
- Overall, using let allows us to declare variables in a safer way.
Further Reading