Variable Scope
This lesson is part of the Web Programming 1 Course.
When you declare a variables with const and let they can only be used within the code block that they are declared. Consider this example:
function checkScore(currentScore){
const highScore = 99;
if(currentScore > highScore){
alert("There is a new high score!");
}
}
alert(highScore); // This line will crash the program!!!
The problem with this code is that because the highScore variable is declared inside the code block that defines the body of the function, it can only be used inside that block. So, the last line of code will result in an error message in the console log that says 'highScore is not defined'.
If you wanted to make use of the highScore outside of the function, then you could declare it outside of the function like so:
const highScore = 99;
function checkScore(currentScore){
if(currentScore > highScore){
alert("There is a new high score!");
}
}
alert(highScore); // Now this line will alert 99
Variable scope in programming refers to parts of a program in which a variable can be used. JavaScript, and many other programming languages follow a rule known as block scoping. This means that a variable can only be used within the block where it is declared.
Here is another example of code that will cause the program to crash because it is attempting to use a variable that is 'out of scope':
const score = prompt("Enter your score.");
if(score > 90){
const grade = "A";
}
alert("Your grade is: " + grade); // This will crash, grade is out of scope!
One way to get this code to work is to declare the grade variable outside of the code block of the IF statement, like so:
const score = prompt("Enter your score.");
let grade;
if(score > 90){
grade = "A";
}
alert("Your grade is: " + grade);
By moving the grade variable declaration outside of the code block of the IF statement (and using let instead of const), we can get the alert to work.
Local and Global Variables
Variables that are declared inside the body of a function are known as local variables, because they cannot be used outside of the function (the variable is can only be used 'locally', within the function body).
Variables that are declared outside of any code block are called global variables, because they can be used anywhere in the program (they can be used 'globally').
Here's an example that includes both a global and local variable:
const salesTaxRate = 0.05;
function calculateTotalCost(price){
const tax = price * salesTaxRate;
return price + tax;
}
The salesTaxRate variable is global, because it is not declared within any code block. The tax variable is local to the calculateTotalCost, and therefore can only be used within the body of the function.
As you gain more experience in programming you will get a feel for where to declare variables. But it is important to know at an early stage about variable scope, and that JavaScript uses block scoping to determine where a variable may or may not be used in a program.