Questioning the need for const in JavaScript

4👍

As far as I can tell, the only reason ctx is stored is so it can be
passed to the Chart constructor,

That’s one reason, yes. Usually developers want to save the ctx as well, as you never know when you might need it. It’s a convention.

there’s no apparent reason to save the myChart variable.

If you don’t ever need to do anything with myChart, you don’t HAVE TO save it. I would. It’s a matter of preference.

So I don’t see why either would need to be const

It’s a good practise to have all variables marked as const, if they are never modified in your code or should never be modified. It probably wouldn’t break anything, even if you used let or var, but in the long run and especially if you work with others, it’s a very good idea to mark variables as const if they shouldn’t be modified.

I don’t see why the myChart variable is even needed.

Well they’ve given you a one way to do it. You don’t have to follow it strictly. It would be a bad use of time to make multiple examples with tiny variations to suit everyone’s specific needs.

The reason it’s an issue is because I need to have several charts on
the same page. So I either need to name them ctx1, ctx2, ctx3, etc.,
or remove the const keyword.

I wouldn’t remove the const, but do that ctx1, ctx2, … solution instead. One ctx for each chart. That’s simply the reality of your situation. The example is for one chart and if you need multiple, you need multiple ctx’s.

Leave a comment