Understanding variables - why is "const" important?

Hello,

I’m trying to understanding the importance between “var”, “let” and “const”.

More specifically, why can’t “var” be used everywhere - replacing “const”.

Thanks for your time,
Phil.

There’s a lot you can read on this… I don’t know what you’ve read about it thus far or what source of information you’re using…

MDN - const

MDN - var

MDN - let

1 Like

The way var works has some issues, mainly to do with the ease it can introduce bugs. Amongst other things:

It’s hoisted, meaning code can be written in a different order to how you might expect for it to work

// this does not trigger an error, it logs undefined
console.log(foo);

var foo;

You can redeclare it, making it easy to accidentally overwrite:

var foo = 1;

// Some other code...

// ...then
var foo = 2;

It will attach to the global object if it’s at the top level:

var foo = 1;
// in a browser, window.foo is now 1

// Some other code

The way JavaScript currently works cannot change. The behaviour of var cannot be altered, otherwise lots of websites would break. So the only way to fix the issues is to add a new feature to the language and tell everyone to use the new feature instead.

6 Likes

To add on that … const adds some clarity and safety. Taking it as a given that we should use let instead of var (and we should 100% should), const gives a little more clarity in the code. Yes, you could use let for everything, like we used to use var for everything. That would work. But const allows us to communicate that that this variable is never to be changed or reassigned. It also prevents it from happening by accident. Is there value in that? A little. If I see a variable declared as a const (OK, an oxymoron), I know that if it is a primitive, it will never change and if it is a reference type, it will never be reassigned. Information is good.

One of the weaknesses of JS is that it is fairly loose with data compared to other languages. That’s why things like TypeScript were invented.

I mean, yeah, you could just use var for everything, but then no one is going to hire you. If a hire candidate was shown to me and they were using var, I would stop reading. And if you use let for everything, people will just assume that you either don’t know how variables work or are too lazy to try to understand your data.

6 Likes

Thanks! I love understanding things, but i guess my reaction sometimes is to try to “feel” the magnitude of a certain data type to the entire code or website.

I think i have to drill a lot of problems with each type, combined with functions to get the feel or impact of it.

How does one know, for instance that someone would love “to the metal programming” ? Is it the “feeling” for direct output from input? But maybe that notion is completely wrong and i just don’t take the time to read instructions two, three times over and follow directions and memorize that “const” is just an abbreviation for constant, which is a straightforward linear math concept.

I’ve heard that once you start learning frameworks, if you don’t have solid fundamentals in .js, its literally chaos…

But this is what i meant in terms of choosing “const” (all three variables give the same result);

let tipCalculator = () => {
let sum = 29.95;
let percentage = 18;
let tip = sum * (percentage / 100);
let total = sum + tip;
console.log( Sum before tip: ${sum}) Tip percentage: ${percentage}% Tip: ${(tip.toFixed(2))} Total: ${total.toFixed(2)} );
};

tipCalculator();


var tipCalculator = () => {
let sum = 29.95;
let percentage = 18;
let tip = sum * (percentage / 100);
let total = sum + tip;
console.log( Sum before tip: ${sum}) Tip percentage: ${percentage}% Tip: ${(tip.toFixed(2))} Total: ${total.toFixed(2)} );
};

tipCalculator();


const tipCalculator = () => {
let sum = 29.95;
let percentage = 18;
let tip = sum * (percentage / 100);
let total = sum + tip;
console.log( Sum before tip: ${sum}) Tip percentage: ${percentage}% Tip: ${(tip.toFixed(2))} Total: ${total.toFixed(2)} );
};

tipCalculator();

Thx again.
Philip

Got it with the new features Dan, thanks, just like the new “arrow functions” i assume…

2 Likes

You can often get the same results, but you should always follow these rules of thumb:

  1. Use const if you can

  2. Use let if you must

  3. Don’t use var

7 Likes

Dan summed up very well why var is left out nowadays and in any contemporary js code, you wont see it used at all. If the reasons var is outdated doesnt click, you shouldnt really worry about it at this point, just refrain using it and if ever in the future the matter becomes important to you, just revise the docs. Your concern should be to learn using let and const. Again, just reading docs wont work. You need to use it, “get a feel” as you expressed. Most things(if not all) require practice and via experience you trully comprehend them.
Initially you can stick to let, you cant go wrong(much) with it. Use const for variables which value you dont intend to change. Once in a while, you will encounter situations when you used const, but it did not fit for the intentions of your code, or you used const anticipating one result, but things turned out differently. Those are the best moments when you can look again the docs for more info, as being put in actual situation with context, things get better meaning. Ideally you want to prioritize const and use it mostly in your code, or at least on projects ive been, const happen to be dominant. After a while, you wont have issues determining which keyword to use.

4 Likes

So if Var is not to be used, what’s the point of it being in JavaScript?

It’s historical. var has existed since the beginning of JavaScript, let and const were only added around 2015 with the ES6 version. If this makes you think "well why didn’t they just remove var", the answer is because that would break millions of websites that are unmaintained and still using var.

4 Likes

Thank you for the detailed explanation! I understand now.

to add to that. Var , let both act the same way of declearing and object. only difference is that var is an old way of declearing an object and is widely supported in older browsers. ’ let ’ itself is the newer way of declearing and object and it is widely supported in all modern browsers. ‘const’ its self means that the object that has being decleared can not be used any were else in your script. I hope this helps

2 Likes

Var and let have very different behaviors with respect to scoping. Var has some somewhat unintuitive behaviors that can lead to bugs if not understood.

Const doesn’t mean that the object won’t be used elsewhere in your script. It means that the variable will only point to this one object.

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.