In the not so distant past there was only one way to define a variable in JavaScript, and that was with var
. However, with the introduction of ES6 two additional ways were added, let
and const
. Wait…why do we need three different ways to do the same thing? Are there instances where one should be used over another? Well, those are some of the questions that I am going to answer for you in this article. But first, we need to have a little discussion about a concept called scope.
JavaScript has two different scopes. The first is function-scope, sometimes referred to as global-scope, and the second is block-scope. Let’s look at a few examples to get a better understanding of the difference between function-scope and block-scope.
function someFunction() {
var foo = 'I am foo!'
console.log(foo); // This prints 'I am foo!' to the console
}
console.log(foo); // ReferenceError: foo is not defined
In the above example, the value of foo
is return on line 4 within the function, but throws an error when we attempt to access foo
outside of the function on line 7. This is because variables defined using var
are function-scoped. They can only be accessed within the function in which they are defined. So what about block-scope?
Let’s add a few more variables using let
and const
, as well as an if
statement to our previous function and see how the scope of these variables differ.
function someFunction() {
if (true) {
var foo = 'I am foo!';
let bar = 'I am bar!';
const baz = 'I am baz!;
console.log(foo); // Prints 'I am foo!' to the console
console.log(bar); // Prints 'I am bar!' to the console
console.log(baz); // Prints 'I am baz!' to the console
}
console.log(foo); // Prints 'I am foo!' to the console
console.log(foo); // ReferenceError: bar is not defined
console.log(foo); // ReferenceError: baz is not defined
}
// Any console logging foo, bar or baz here will return a RefferenceError
As you can see in lines 7–9, all of the console.log()
statements within the if
statement return the expected variable values. However, upon inspection of lines 12–14, we begin to see some differences. On line 12, the value for foo
is displayed in the console, but lines 13 and 14 return ReferenceError for bar
and baz
. This is because let
and const
are block-scoped!
#javascript #javascript-tips #javascript-scope #es6