DEV Community

Cover image for Let vs Var in JS
Manu Martinez
Manu Martinez

Posted on • Edited on

Let vs Var in JS

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);
Enter fullscreen mode Exit fullscreen mode

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",
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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