Modern Scoping and Functions
Introduction: Welcome To Modern JavaScript
Welcome to the first lesson of Modern JavaScript Syntax Foundations. In this course, we will explore how Modern JavaScript has evolved to become more reliable and easier to read. Most of these changes began with a version called ES6, which was released in 2015. This version changed the way developers write code every day.
In this lesson, we will focus on the building blocks of modern code. You will learn how to manage data using modern variables and how to write functions that are shorter and smarter. All the code we write will run directly in the CodeSignal IDE. You do not need to install anything on your computer right now, as the environment is already set up for you.
The Problem With Var
In the early days of JavaScript, we only had one way to create a variable: using the var keyword. However, var has a specific behavior that often causes bugs. It does not respect block boundaries. A block is simply the code found inside curly braces { }, such as an if statement or a for loop. Instead, var is scoped to the nearest function, or globally if it is declared outside a function.
If you create a variable with var inside an if statement, that variable "leaks" out and can be used anywhere in the function. This makes it easy to accidentally change a value you did not mean to touch.
Output:
In this example, the variable named legacy is created inside the if block. Even though the block ends, the variable is still accessible outside of it. In a large project, this behavior can lead to many confusing errors because variables do not stay where they are put.
Block Scoping With Let And Const
To fix the problems caused by var, modern JavaScript introduced let and const. These keywords use block scoping. This means that if you define them inside curly braces { }, they stay inside those braces. They cannot be accessed from the outside.
The difference between the two is simple. You use let when you plan to change the value of the variable later. Use const when the variable should not be reassigned. Note that objects and arrays declared with const can still be mutated. In professional code, we prefer const by default because it makes the code more predictable.
Output:
In this code, both modern and fixed are protected. If you tried to use them after the if block, the program would stop and show a ReferenceError. This behavior helps you keep your code organized and prevents variables from interacting with each other in unexpected ways.
