Original link: https://www.sey.ink/5367/
Explore the differences between the var and let keywords
One of the biggest problems with declaring variables with the var
keyword is that you can easily override the variable declaration:
var camper = "James"; var camper = "David"; console.log(camper);
In the code above, the camper
variable is initially declared as James
and then overridden as David
. Then the console displays the string David
.
In small applications, you probably won’t have this kind of problem. But as your codebase grows, you may accidentally overwrite a variable you didn’t intend to overwrite. Since this behavior does not raise an error, it becomes more difficult to search for and fix the error.
A keyword called let
was introduced in ES6, a major update to JavaScript to address potential issues with the var
keyword. You’ll learn about other ES6 features in later challenges.
If you replace var
with let
in the code above, it will cause an error:
let camper = "James"; let camper = "David";
The error can be seen in your browser console.
So unlike var
, when you use let
, a variable with the same name can only be declared once.
Declare read-only variables using the const keyword
The let
keyword isn’t the only new way to declare variables. In ES6, you can also declare variables using the const
keyword.
const
has all the great features of let
with the added benefit that variables declared with const
are read-only. They are a const value, which means that once a variable is assigned const
, it cannot be reassigned:
const FAV_PET = "Cats"; FAV_PET = "Dogs";
The console will display an error due to reassignment of the value of FAV_PET
.
You should always use the const
keyword to name variables that you don’t want to reassign. This helps avoid additional reassignments to a constant.
Developers will use uppercase letters for constant identifiers and lowercase letters or camelCase names for variable (object or array) identifiers
The first touch of javascript, variable definition first appeared on Sensen blog .
This article is reprinted from: https://www.sey.ink/5367/
This site is for inclusion only, and the copyright belongs to the original author.