Local and Global Variables

Declaring and Using Variables

Local and Global Variables

🙋 Need help? Ask an expert now!

Variables are either local or global. Local variables are declared with the keywords var, let, or const while global variables are usually declared without any keywords. The keywords var, let, or const are not exactly the same, as shown below:

  • var - the variable lives in the scope of the current function or in the global scope
  • let - the variables lives in the current scope
  • const - like let, but cannot be reassigned

The sample program above consists of two variables, a and b. Variable a is a global variable while b is a local variable. This is the reason why a can be printed anywhere in the program while b can only be printed inside the function print(). Since we haven't touched on functions yet, ignore the function statement and look for the difference between a and b. Since b is called inside the function, it can only be used within the function. It does not "exist" anywhere else in the program. If you haven't tried this already, try removing the comments for console.log(b) and run the program to see what happens when you try to access a local variable outside of its scope.

Edit Me on GitHub!

Application Question

Consider the following code segment:

sum = 0;
function add() {
    let firstNumber = 10;
    let secondNumber = 20;
    console.log(sum);                           // Statement 1
    console.log(firstNumber);                   // Statement 2
    return firstNumber + secondNumber;

console.log(sum);                               // Statement 3
console.log(sum + add());                       // Statement 4
console.log(sum + firstNumber + secondNumber);  // Statement 5

Which console.log() statement will throw an error?