20

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?

4
  • 3
    const variables cannot be changed. let is probably the best choice otherwise. Commented Apr 13, 2023 at 22:35
  • w3schools.com/js/js_variables.asp Commented Nov 17, 2023 at 4:09
  • 1
    Check this. Explained with example shunyitytechsolutions.com/blog/… Commented Mar 26, 2024 at 9:49
  • Ah...but the statement "const variables cannot be changed" is very misleading. A better statement is "const variables can not be reassigned to, but their content can still be changed!" Commented Oct 5 at 18:38

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.