Yeah π€. Today we must starting learning more about how really JS works. It should be really strange but don't worry about that, I will try to make it really clear and understandable to make sure that you have just understood it π₯°
First of all, we should understand π what is exactly a variable, a variable is a container when you can save whichever data you need, think in a container, you can save a data inside it and make sure that it will be safe π€. The main point is that it will be safe until your program die, let's doing an example:
var myName = "Manu"
console.log(myName);
As you can see above, we have just made a brief example where we have saved up my name into a value π€, but STOP, saving data inside var
is really dangerous, it hasn't had any scope, the data can change whenever you want, imagine that this data need to be always the same, it means isn't able to change it, then I introduce you constants
, let's see an example:
const myName = "Antonio",
This is exactly what a constant looks like, his value will never change, you can be sure of that. But then, π΅βπ«
What are the different between var
and const
?.
The const will never mutate π. This is the key.
Nevertheless, there are another way to get a variable
in JS, and it's the best approach to make your vars
more secure, it's a pleasure to meet you let
, let's see an example:
let myAge = 20;
console.log(myAge);
What is exactly that π€?
Apparently it's the same meaning that var
, it's able to mutate and re-asign a new value, but let
is block-scope
, it means understand what is exactly a scope, then if you declare it inside an if it won't never mutate π€, let's see an example:
if (true) {
var myName = "Manu";
}
myName = "Antonio";
In this code, we can mutate the value from the var
because var
doesn't understand why it shouldn't mutate, however look at the following example:
if (true) {
let myName = "Manu";
}
myName = "Antonio";
Oh shit π©!!!, it gets an error because let
understand that you have just declared inside an if
scope, then why did you want to mutate this value? Here, you can see clearly which is the difference between let
and vars
.
I hope you have just understood βΊοΈ why using a var is a good practice when you are writing your code. If you have any question please don't hesitate to write a comment π, it will be a pleasure to help you.
Top comments (0)
Some comments have been hidden by the post's author - find out more