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.
Answer from nixanosize on Stack OverflowWhen should you use "var", "let", or "const" in JavaScript code - Stack Overflow
constants - In JavaScript, why should I usually prefer 'const' to 'let'? - Stack Overflow
JS <> const vs let = should I always use const?
javascript - How much should I be using 'let' vs 'const' in ES6? - Software Engineering Stack Exchange
Videos
Hi everyone!
I'm pretty new to web development and have started to read a little bit about javascript. Right now I'm trying to learn how to declare a function but realized that there is different ways to do this using var, let or const. Since I'm new to this, most of the explanation on the internet is pretty advanced to understand atm, so could anyone explain the differences for me very short short and easy, alternatively give me a link that explain it in pretty easy terms?
Thanks in advance!
(Edit: Thank you so much for the answers, rly appreciate it!)
Basically,
- use
letif the variable's value will change during the code - use
constif it won't and you / your team want to useconstin those situations in the project you're working on; it's a matter of style
If you do use const, then it's surprising how often it turns out that the guidelines above mean you use const because you end up not needing to change a variable's value (if you're following the usual rules of keeping your functions of reasonable size and such). (Well, it surprised me, anyway...)
Using const when the variable's¹ value is not meant to change accomplishes a few things:
It tells others reading your code that you don't intend the value to change.
It gives you a nice proactive error if you change the code so it writes to that variable. (A decent IDE can flag this up proactively, but if not, you'll get the error when running the code.) You can then make an informed, intentional decision: Should you change it to
let, or did you not mean to change that variable's value in the first place?It gives a hint to the JavaScript engine's optimizer that you won't be changing that variable's value. While the engine can frequently work that out through code analysis, using
constsaves it the trouble. (Caveat: I have no idea whether this is actually useful to the JavaScript engine. It seems like it would be, but runtime code optimization is a very complicated and sometimes non-intuitive process.)
¹ Yes, it's funny to use the term "variable" to refer to something that by definition doesn't vary. :-) The specification's term is "binding," but I bet you won't hear people talking about "bindings" in everyday conversation anytime soon... So the aggregate term will probably remain "variable" except when we can specifically refer to something as a "constant."
Using const by default is essentially a matter of programming style. However there are pros and cons to each:
Arguments in favor of using const by default
The arguments in favor of using const by default are the following:
- It avoids side effects caused by involuntary reassignments;
- During a code review, it removes an uncertainty, because the developer who sees a
constvariable can count on the certainty that it will not be reassigned; - Maybe we could say it is more consistant with functional programming and immutable states.
- With TypeScript, there are some cases with better inferences.
Here is an example of advantage when using const with TypeScript:
const hello = "Hello" as string | undefined
if (hello !== undefined) {
["A", "B"].forEach(
name => console.log(`${hello.toUpperCase()}, ${name}`) // OK
)
}
With let, in strict mode, TypeScript detects an error:
let hello = // …
// …
name => console.log(`${hello.toUpperCase()}, ${name}`)
// ^__ error here: Object is possibly 'undefined'.
Arguments in favor of using let by default
I summarize here the article Use “let” by default, not “const” that gives arguments in favor of using let by default rather than const:
- Re-assignment is not a dangerous thing, it is just... usual;
- If a variable could be reassigned, then it should be declared with
let, because it is more expressive to reserveconstfor real constants; constis misleading because it doesn’t stop references being modified;- It is two more characters to write and to bundle;
- Using
constby default is inconsistant with function parameters; - There is no performance gain to use
const.
Since we can change the value of const by changing the object it is pointing to, then is it preferable to always use const? I'm probably getting a little ahead of myself, but I was just curious.
My reply here is not javascript-specific.
As a rule of thumb in any language that lets me do so in a semi-easy way I'd say always use const/final/readonly/whatever it is called in your language whenever possible. The reason is simple, it's much easier to reason about code when it is dead obvious what can change and what cannot change. And in addition to this, in many languages you can get tool support that tells you that you are doing something wrong when you accidentially assign to a variable that you've declared as const.
Going back and changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.
How many bugs have you seen that involved variables changing unexpectedly? I'd guess a lot. I know that the majority of bugs that I see involve unexpected state changes. You won't get rid of all of these bugs by liberally using const, but you will get rid of a lot of them!
Also, many functional languages have immutable variables where all variables are const by default. Look at Erlang for example, or F#. Coding without assignment works perfectly in these languages and is one of the many reasons why people love functional programming. There is a lot to learn from these languages about managing state in order to become a better programmer.
And it all starts with being extremely liberal with const! ;) It's just two more characters to write compared to let, so go ahead and const all the things!
Be careful, because const object keys are mutable.
From here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
object keys are not protected
consider this example:
const colors = {red: "#f00"};
console.log(colors); // { "red": "#f00" }
colors.red = "#00f";
colors.green = "#0f0";
console.log(colors); // { "red": "#00f", "green": "#0f0" }
Same thing for arrays:
const numbers = [1, 2, 3];
console.log(numbers); // [ 1, 2, 3 ]
numbers.push(4);
console.log(numbers); // [ 1, 2, 3, 4 ]
I haven't decided totally myself, but I'm considering using const for all non-array/non-objects and use let for objects/arrays.
The difference between let and const is that once you bind a value/object to a variable using const, you can't reassign to that variable. In other words Example:
const something = {};
something = 10; // Error.
let somethingElse = {};
somethingElse = 1000; // This is fine.
The question details claim that this is a change from ES5 — this is actually a misunderstanding. Using const in a browser that only supports ECMAScript 5 will always throw an error. The const statement did not exist in ECMAScript 5. The behaviour in is either JS Bin being misleading as to what type of JavaScript is being run, or it’s a browser bug.
In practice, browsers didn't just go from 0% support for ECMAScript 2015 (ECMAScript 6) to 100% in one go — features are added bit-by-bit until the browser is fully compliant. What JS Bin calls ‘JavaScript’ just means whatever ECMAScript features your browser currently supports — it doesn’t mean ‘ES5’ or ‘ES6’ or anything else. Many browsers supported const and let before they fully supported ES6, but some (like Firefox) treated const like let for some time. It is likely that the question asker’s browser supported let and const but did not implement them correctly.
Secondly, tools like Babel and Traceur do not make ES6 ‘run’ in an older browser — they instead turn ES6 code into ES5 that does approximately the same thing. Traceur is likely turning const statements into var statements, but I doubt it is always enforcing that the semantics of a const statement are exactly replicated in ES5. Using JS Bin to run ES6 using Traceur is not going to give exactly the same results as running ES6 in a fully ES6 specification-compliant browser.
It is important to note that const does not make a value or object immutable.
const myArray = [];
myArray.push(1); // Works fine.
myArray[1] = 2; // Also works fine.
console.log(myArray); // [1, 2]
myArray = [1, 2, 3] // This will throw.
Probably the best way to make an object (shallowly) immutable at the moment is to use Object.freeze() on it. However, this only makes the object itself read-only; the values of the object’s properties can still be mutated.
What you're seeing is just an implementation mistake. According to the ES6 spec wiki on const, const is:
A initialize-once, read-only thereafter binding form is useful and has precedent in existing implementations, in the form of const declarations.
It's meant to be read-only, just like it currently is. The ES6 implementation of const in Traceur and Continuum are buggy (they probably just overlooked it)
Here's a Github issue regarding Traceur not implementing const