This content originally appeared on Go Make Things and was authored by Go Make Things
On Monday, we looked at the difference between let
, const
, and var
(and why you should mostly just use let
). Yesterday, we learned how scope works.
Today, we’re going to combine these topics and look at block scoping in JavaScript. Let’s dig in!
What is block scoping?
In JavaScript, a block is anything that appears between a set of curly brackets ({}
).
// This is in the global scope
let answer = null;
let question = false;
// This is a block
if (question === true) {
// This in a block scope
let answer = 42;
}
let
and const
behave differently than var
with block scope
The let
and const
keywords provide block-scoping. The var
keyword does not.
That means that if you declare a variable with var
, then use var
to declare another variable with same name inside a block scope, the original variable will be updated. If you use let
or const
, a new variable contained within the block scope is created.
var sandwich = 'tuna';
let drink = 'soda';
if (true) {
// drink is in the block scope, but sandwich is not
var sandwich = 'turkey';
let drink = 'water';
// logs "turkey"
console.log(sandwich);
// logs "water"
console.log(drink);
}
// logs "turkey"
console.log(sandwich);
// logs "soda"
console.log(drink);
Because let
and const
provide block-scoping, they are almost always a better choice than var
.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-02-10T15:30:00+00:00) let, const, and block scoping in JavaScript. Retrieved from https://www.scien.cx/2021/02/10/let-const-and-block-scoping-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.