This content originally appeared on DEV Community and was authored by Marlon Munoz
let, var , const? when do we use this variables really?
Back in 2018, I got the opportunity to play around a little bit with JavaScript. During that year, I was thrilled to learn how this language performs. The first thing I learned was to declare a variable. My first variable was var name = 'el marlo'
after I so this variable be used within my function and console.log(name) // => el marlo
. As a beginner programmer, I got excited. Fast forward to 2024, officially starting my journey into Software Engineering, getting my hands into JavaScript after so many years and a lot of this have changed. The first thing I noticed, there were more options to declare a variable? What is let
and const
, I was only familiar with var
.
var
var
is the oldest keyword for declaring variable. Therefore, let's address the difference against the other two: let
and const
to help us decide which one should go into our code.
I learned that var
was a keyword that if you are planning to use, to be very careful or don't use it at all due to a lacking in block scope or in plain english, the code that goes inside the curly braces {}. In addition, it can create bugs in your code because var
variables can be re-declared and updated:
var favHobby = "Eskate";
var favHobby = "Sleeping";
var favHobby = "Joking";
console.log(favHobby); // => Joking
console.log(favHobby); // => Joking
console.log(favHobby); // => Joking
let
let
is the update version of var
. This variable is blocked scoped, which means that unlike var
, anything that we declare within {curly braces will only be available within this scope}
:
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// Expected output: 2
}
console.log(x);
// Expected output: 1
Example from: mdn web docs
In addition, let
can be updated but NOT re-declared.
const
const
is the more reliable variable to used for the following reasons: const
declarations are block scoped: which means it is only accessible {within the block}
. Another strong reason is, const
cannot be updated or re-declared unless it is an object. If const
was an object
, then properties could be added, removed or updated.
const number = 42;
try {
number = 99;
} catch (err) {
console.log(err);
// Expected output: TypeError: invalid assignment to const 'number'
// (Note: the exact output may be browser-dependent)
}
console.log(number);
// Expected output: 42
This content originally appeared on DEV Community and was authored by Marlon Munoz
Marlon Munoz | Sciencx (2024-07-28T07:24:11+00:00) let, var or const, what’s the difference?. Retrieved from https://www.scien.cx/2024/07/28/let-var-or-const-whats-the-difference/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.