Variables and Scope

In this lesson, you will learn how variables and scope work in modern JavaScript.

Variables

A variable is a named container with a unique name for storing data values. The statement below declares a variable with the name “car”:

let car;

console.log(car); // undefined

In JavaScript, variables are initialized with the value of undefined when they are created. You can assign a value to a variable using the assignment operator (=) when you declare it:

let car = 'Volvo';

console.log(car); // Volvo

Always initialize your variables before you try using them or you will get an error:

console.log(car); // ReferenceError: car is not defined

let car = 'Toyota';

ECMAScript 2015 (or ES6) introduced two new ways of declaring variables, let and const. These new keywords were introduced to fix the bugs caused by the confusing function scoping of var.

Scopes

By scope, we mean the visibility of variables in the different parts of our code during runtime. In other words, scope is the part of the code that can access and modify a variable.

In JavaScript, there are two types of scope:

  • Global scope
  • Local scope

What changed with Modern JavaScript is the way we use variables in the local scope.

JavaScript scopes
JavaScript scopes

Global scope

A variable declared outside a function becomes global. This means it can be accessed and modified everywhere in the code.

We can declare constants in the global scope:

const COLS = 10;
const ROWS = 20;

We can access them from all parts of our code.

Local scope

Variables declared in a local scope cannot be accessed from outside of that scope. The same variable name can be used in different scopes because they are bound to their respective scopes.

Local scope differs depending on the variable declaration used.

Function scope

Variables declared with the var keyword become local to the function. They can only be accessed from within the function.

function printCar() {
  if(true) {
    console.log(car); // undefined
    var car = "Porsche";
    console.log(car); // "Porsche"      
  }
  console.log(car); // "Porsche"
}

printCar();
console.log(car); // ReferenceError

You can see that we don’t get an error even though we access car before the declaration. Variables declared with the var keyword are hoisted, meaning they’re moved to the top of the function and initialized with undefined before the code is run. With the hoisting, they are accessible in their enclosing scope even before they are declared.

Can you see how this can get confusing? If you don’t understand it completely, don’t worry; we are not using var with function scoping within this course. However, it’s good to know that it exists.

Block scope

The concept of block scope was introduced in ES6 with the new ways to declare variables: const and let. This means that the variable is accessible between two curly braces {}, for example inside an if or for.

function printCar() {
  if(true) {
    console.log(car); // ReferenceError
    const car = "Fiat";
    console.log(car); // "Fiat"      
  }
  console.log(car) // ReferenceError
}

printCar();
console.log(car); // ReferenceError

The let and const variables are not initialized until their definition is evaluated. They are not hoisted as in function scoping. Accessing them before the initialization results in a ReferenceError.

You can see how this is easier to comprehend. We are using block scoping with let and const in this course.

Const vs let

Now that we know that we should use let and const, which should we use?

The difference between the two is that the value of a const can’t be changed through reassignment, and it can’t be redeclared. So, if we don’t need to reassign, we should use const. This also makes the code clearer since we have one variable to represent one thing.

You can always declare the variables as const until you see that you need to reassign the variables and then change them to let. One example of when you need let is in loops:

for(let i = 0; i < 10; i++) {
  console.log(i); // 1, 2, 3, 4 ...
}

Conclusion

  • Variables declared on the global scope are accessible everywhere in your code.

  • Variables declared in a local scope cannot be accessed from outside that scope.

  • Primarily use const for variables whose values will never change.

  • For everything else use let.

  • Don’t use var to avoid confusion.


Quiz on variables and scope

Assess what you’ve learned about variables and scope in this quiz challenge.

1

What kind of scope do const and let have?

A)

Global scope

B)

Block scope

C)

Function scope

Question 1 of 40 attempted