Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use "var", "let", or "const" in JavaScript code [duplicate]

Tags:

javascript

New to JavaScript and a beginner. I came across JavaScript variables and realized there are three different ways to go about them (var, let and const). Do they each have a specific purpose or you can just use one throughout?

Made some searches on google and apparently var is for old browsers but I want to find out from actual developers, which one is best to use in this day and age? Or it doesn't really matter?

like image 899
Maame Afia Avatar asked Dec 01 '25 01:12

Maame Afia


1 Answers

In my opinion nowadays it is better to use let and const.

According to the ES6 standard, these options are more convenient with their scope. Both give us the so-called block scope. This means that the scope of their use can be limited to a block of code, such as a for loop or an if expression. This gives the developer more flexibility in choosing the scopes of variables.

In addition, if we consider these options, then you will not be able to change the variable declared with const, unlike var and let.

Generally speaking, let and const are often used now, depending on the need.

like image 135
nixanosize Avatar answered Dec 02 '25 15:12

nixanosize



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!