What is Variable Scope In JavaScript?

Introduction

Variables are commonly used in every programming language. They are useful for storing data and act as containers in programming to process logic while writing functions. Today, we will learn about variable scope in JavaScript. We will first explain this from the perspective of programming, and then we will focus on what variable scope means in JavaScript, which is the topic of this discussion.

What is Variable Scope in Programming?

In the phrase variable scope, the word scope refers to the range or boundary within which a variable can be accessed. In programming, variable scope determines the range within which a variable can be accessed. It entirely depends on where you declare your variable. Variable scope is mainly divided into two types: global scope and local scope.

Global Scope:

Global Scope means a variable declared outside any block or function Since it is not enclosed within any specific structure, it is accessible globally throughout the entire program, whether you use it within a function or a block of code. All you have to do is ensure it is correctly declared at the top of the program. Due to its properties, it is known as a Global Scope variable.

A real-life example might help clarify this concept:

"A government hospital in your city—everyone in the entire country can access this government hospital at no cost."

Local Scope:

Local scope is a variable scope where a variable is declared within a specific block of code or function, meaning the variable is only accessible within that block or function. Since it is not declared globally, it is only accessible within that limited scope. For this reason, it is known as a Local Scope variable.

A real-life example might help illustrate this:

"A military base in any country where civilians are not allowed to enter, except for military personnel."

Why Variable Scope?

Proper knowledge of variable scope is crucial for a programmer, as it is one of the fundamental concepts to understand in any programming language. It’s important to master this concept early on, as it directly impacts how code is written and debugged. After investigating the different types of this, you should have a clear understanding of why it is so essential.

Knowing variable scope helps developers debug code faster and more effectively. A developer with a solid understanding of variable scope can easily determine where a specific variable is declared, how it changes throughout the program, and how long it remains accessible. This makes tracking down errors and understanding data flow much easier.

Variable Scope in JavaScript

In JavaScript, it works similarly to other languages, but with some unique characteristics. Variables can be declared using three keywords: var, let, and const. Each of these has different scoping rules, which we will explore today.

  • var has function-level scope, meaning a variable declared with var is accessible throughout the entire function in which it is declared.
  • let and const have block-level scope, meaning a variable declared with either of these is only accessible within the block (such as a loop or conditional) in which it is declared. Additionally, const creates a read-only variable, making it immutable after assignment.

Understanding the differences between these keywords is crucial for managing variable scope in JavaScript and ensuring that variables are used correctly.

var keyword

var: Earlier, before 2015, in JavaScript, the var keyword was used for declaring variables. However, there was an issue with it: unlike other languages, it didn’t support variable scope properly. A variable declared using var was accessible everywhere in the program, regardless of whether it was declared outside of a function or block or within them. This caused JavaScript to have issues with variable scope. As JavaScript grew rapidly in the last few decades, this issue needed to be addressed. Finally, in the 2015 updates (ES6), JavaScript introduced two new keywords, let and const, to provide proper variable scope, similar to other programming languages. You can see the examples below for a better understanding.

JavaScript

copy

var name = 'john';
var name = 'harry';

console.log(name)
// output = ‘harry’;

In the example above, we used var to declare the variable name and assigned it the value John. On the second line, we declared the variable name again and assigned it a new value, Harry. It returned the output without any error.

This shows that var allows the redeclaration of a variable with the same name. This is a weak point of var, as it poses a risk of accidental variable overwriting, especially in large projects. This made it quite difficult for developers to work on projects before the 2015 ES6 updates.

JavaScript

copy

// block of code
{
  var name = 'john';
}

console.log(name);
// output: 'john'

In example above, even though we declared the variable name within a block of code, it was still accessible globally. This is because var does not respect block-level scope. As a result, when we tried to access name outside the block, it returned the value john.

JavaScript

copy

function greetUser() {
  var name = 'John';  // 'name' is only accessible within this function
  console.log('Hello, ' + name);  // This works because 'name' is in the same scope
}

greetUser(); // Logs: Hello, John

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

However, var does support function scope. After the block example, we created a function greetUser, and within that function, we declared a variable name. We then called that variable within the function, and it returned the expected output. But when we tried to access the same variable outside the function, we received an error (Error: name is not defined), confirming that the variable name is scoped locally to the function.

var doesn’t support variable scope properly like other languages, and it also allows us to declare the same variable multiple times. Due to these weaknesses, it is not recommended to use it in JavaScript instead, it is recommended to use let and const.

let keyword

let It is a keyword that was introduced in JavaScript ES6 in 2015 updates along with const. It is widely used in JavaScript as it is recommended for variable declaration. It is well-aligned with the variable scope conventions of other languages. Unlike var, it doesn't allow redeclaring the same variable more than once, which makes it more effective. However, it does allow the reassignment of values to the same variable. You can see the examples below for a better understanding:

JavaScript

copy

let name = 'john';
let name = 'harry';

console.log(name)
// output: SyntaxError: Identifier 'name' has already been declared

As you can see in example, we declared a variable using the let keyword, then tried to redeclare the same variable, which threw an error. This demonstrates that this doesn’t allow redeclaring the same variable.

JavaScript

copy

/// block of code
{
  let name = 'john';
  console.log(name); // output: john 
}

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

In the example above, we declared a variable name inside a block of code using the let keyword, and then called it within the same block, which returned the output john. But when we tried to access it outside the block, it resulted in an error: name is not defined. This shows that this supports block scope (local scope).

JavaScript

copy

function greetUser() {
  let name = 'John';  // 'name' is only accessible within this function
  console.log('Hello, ' + name);  // This works because 'name' is in the same scope
}

greetUser(); // Logs: Hello, John

console.log(name); // Error: name is not defined

In the example above, we see that let also supports function scope, as it behaves similarly to var within a function, but without allowing redeclaration. In this example, the name is only accessible within the function greetUser(). Outside the function, attempting to access it results in a ReferenceError. let also supports global scope if you declare a variable outside of any block or function.

JavaScript

copy

let name = 'john';
{
  console.log(name); // output: john
}

function greetUser() {
  console.log(name); // output: john
}

greetUser(); // output: john

const keyword

const: It was also introduced in the JavaScript ES6 (2015) updates alongside the let keyword. It is similar to let, but the key difference is that it doesn’t allow reassigning a value to the same variable, nor does it allow redeclaring the variable. It is a constant in terms of reassignment, meaning the value can only be assigned once. However, if the variable holds an object or array, its contents can still be modified. You can check the example below:

JavaScript

copy

const name = 'john';
name = 'harry';

console.log(name);
// output: TypeError: Assignment to constant variable.

As you can see in the example above, we declared a variable with const and assigned it the value john. On the second line, we attempted to reassign a new value, harry, to the name variable, as we could with let. However, unlike let, this threw an error: TypeError: Assignment to constant variable. which means that you cannot reassign a value to a variable declared with const. This is the main difference between const and let, though both share the feature of block-level scoping.