JavaScript: Understanding Variables and Scope
An in-depth look at variables and scope in JavaScript, covering hoisting, closures and the 'temporal dead zone'.
Listen to Article
JavaScript: Understanding Variables and Scope
What are variables?
-
In programming, variables are simply containers used to store data.
-
You can think of a variable as a box with a label:
- The label corresponds to the variables name (e.g.
username,num1,isLoggedIn, etc.). - The contents inside the box are the values that we are storing (e.g.
"user1",100,true).
- The label corresponds to the variables name (e.g.
- Working with variables involves three key concepts:
- Declaration (Creating the box). This is where we instruct the computer to create a variable and give it a name.
- Initialisation / Assignment (Putting something inside the box). This is where we give the variable we declared a value. We do this with the assignment (
=) operator. - Retrieval / Usage (Looking inside the box). This is where we access the contents of the variable (the value we stored) to use it in our code.
Here is a quick example of variables in JavaScript:
Why do we need variables?
- To store data. Throughout the lifecycle of a program, data will need to be tracked so it can be used later on.
- To make code that is reusable. Variables allow us to generalise our code so that it works no matter what values are assigned to it (e.g. we can write formulas with variables -
totalPrice = itemPrice * taxRate). - To handle data that changes. Over the course of a programs runtime things will change. Variables allow us to track and update that changing state.
- To improve code readability and make code easier to maintain.
What are 'data types'?
- Data can come in different forms. In other words, there are different 'types' of data.
- Some common data types in JavaScript include:
What is 'scope'?
Scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use.
- To put it more simply, scope determines where in your code a variable can be seen and used.
Why does scope matter?
- For security and encapsulation. Scope prevents unintended parts of the codebase from accessing or mutating sensitive data.
- For namespace management. Scope allows you to reuse variable names in different parts of your code without conflicts.
- For garbage collection. Allows the computer to free up memory once variables fall out of scope.
What are the different types of scope?
Global scope
- The global scope is any variables declared outside of any function or block.
- Globally scoped variables can be accessed from anywhere in the entire program.
- Global variables should be used sparingly as they can often lead to bugs as their values can be changed from anywhere in the program.
Local Scope / Function Scope
- The local scope is any variable declared within a specific function or block of code (such as inside an
ifstatement orforloop dependant on the language). - Locally scoped variables can only be accessed from within that specific function or block.
- They are usually cleared from memory once the function finishes running.
Block Scope
- The block scope encompasses any variables that are declared inside curly braces (
{}). - Variables declared with
letandconstin JavaScript are block scoped. - Example:
What is 'Lexical Scope' in JavaScript?
- Lexical scope (or static scope) means that variable accessibility is determined entirely by where the variables and blocks are physically written in your source code.
- JavaScript uses the physical structure of your code to decide which variables are available. Where you call a function doesn't matter; where you write it does.
- Because scope is lexically determined, you can look at a piece of code and trace with absolute certainty which variables a function has access to just by reading the nesting structure.
- Example:
The scope chain
- When looking for a variable, JavaScript always starts looking in the innermost current scope and moves outwards from there.
- If a variable isn't found in the current scope, it steps up to the parent scope, then the parent of the parent scope, and so on.
- As soon as JavaScript finds the variable, it stops searching and uses it.
- If it reaches the global scope and still can't find it, it either throws a
ReferenceErroror creates a global variable (in non-strict mode).
How do you declare variables in JavaScript?
- JavaScript provides three keywords for variable declaration. Here is a quick overview of each:
var keyword
varis the legacy method of declaring variables.- Since the introduction of
letandconstin ES6 (ECMAScript 2015),varis generally considered to be outdated so its usage should be avoided. varis function scoped.- Variables defined with
varcan be redeclared in the same scope. - Variables defined with
varcan be reassigned. - Variables defined with
vardo not have to be initialised. Their value will default toundefined.
let keyword
letis the modern method for declaring variables in JavaScript.letwas introduced in ES6 (ECMAScript 2015).letis block scoped, meaning variables declared withletare only accessible within the nearest enclosing block ({}) in which they are defined.- Variables defined with
letcannot be redeclared within the same scope. - Variables defined with
letcan be reassigned. - Variables defined with
letdo not have to be initialised. Their value will default toundefined.
const keyword
- The
constkeyword is JavaScript's method for declaring constants. constwas introduced in ES6 (ECMAScript 2015).constis block scoped, meaning variables declared withconstare only accessible within the nearest enclosing block ({}) in which they are defined.- Variables defined with
constcannot be redeclared. - Variables defined with
constcannot be reassigned. - For objects and arrays declared with
const, the reference is immutable, but the internal contents/properties can still be modified.
What is hoisting in JavaScript?
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code.
- To put it simply, hoisting is a mechanism in JavaScript where variable and function declarations are moved (or "hoisted") to the top of their containing scope.
- This happens during the compilation phase, before the code is executed line by line.
- JavaScript only hoists declarations, not initialisations.
- This means that the variable names are stored in memory during compilation, but their assigned values remain where they are in the code until execution reaches them.
How does hoisting behave?
var hoisting
- Variables declared with
varare hoisted to the top of their scope. - They are initialised with a value of
undefined. - This means you can reference the variable before it is declared in your code without throwing a syntax error, but its value will be undefined until the assignment line is reached.
- Example:
let and const hoisting
- Variables declared with
letandconstare also hoisted. - But they are not initialised with
undefined. - Instead, entering the scope places them in a Temporal Dead Zone (TDZ) from the start of the block until the declaration line is evaluated.
- Attempting to access them during this window throws a
ReferenceError. - Example:
What exactly is the Temporal Dead Zone (TDZ)?
- The Temporal Dead Zone (TDZ) is the span time from the start of a block or scope until a
letorconstvariable is fully declared and initialised. - During this zone, the variable does exist in memory (meaning it has been hoisted), but the JavaScript engine does not allow you to access it.
Why does the Temporal Dead Zone (TDZ) exist?
- The Temporal Dead Zone (TDZ) was introduced in ES6 (ECMAScript 2015) with the purpose of addressing the design flaws and silent failures baked into
varhoisting. - Before ES6 (ECMAScript 2015), JavaScript only had function scope (
var), which led to messy variable leaking, confusing hoisting behaviour, and accidental global pollution. - Example:
- This confusing behaviour still persists with
var, which is why it should be used sparingly.
What are 'Closures'?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time.
- A closure is created whenever a function is bundled (enclosed) with references to its surrounding state (its lexical environment).
- A closure gives an inner function access to an outer function's scope, even after the outer function has finished executing and returned.
- Normally, when a function finishes running, its local variables are cleared from memory by the garbage collector.
- However, if an inner function retains a reference to those outer variables (often by being returned or passed elsewhere), those variables stay alive in memory.
- Example - Closures are frequently used to create private variables that cannot be modified directly from the outside:
Stay Connected
Get notified whenever we publish new articles, insights, guides and product updates.