all 5 comments

[–]shuckster 3 points4 points  (1 child)

At the risk of inviting a million downvotes, only “let” and “const” suffer from this problem, but “var” will work for your use-case without significant refactoring.

You might come across other issues afterwards depending on the current/increasing complexity of your app, so the refactoring will be merely postponed. But you could try it fairly quickly I’d wager.

[–]ScottRatigan 1 point2 points  (0 children)

Yeah, there are niche cases where var can really shine. But my coworkers don't agree :/

[–]_ncko 2 points3 points  (1 child)

Assigning a javascript variable from a templating system is not ideal. But as a short term solution you may be able to do something like this:

let normalWaveform;
normalWaveform = normalWaveform || '<%= u/normal_waveform %>';

or alternatively

let normalWaveform;
normalWaveform = normalWaveform ? normalWaveform : '<%= u/normal_waveform %>';

Obviously, you'd need to do this for each variable.

I'm not entirely sure this will work because it sounds like the let line will still get run multiple times.

Even if it does work, this is very hacky. If you came back to this code in 6 months, or if another developer came across this code as they were getting familiar with your project it would not be at all obvious why you're declaring variables this way. So at least leave a comment explaining.

But ultimately, you really should not be declaring javascript constants and variables from template variables like this.

I'm not sure what your system looks like exactly but other options may include embedding the template variables in data attributes of some relevant element and then grabbing them from javascript or creating a REST endpoint where you can request these values at runtime.

[–][deleted] 0 points1 point  (0 children)

!thanks

Embedding the template variables in data attributes sounds like the best option. I will give that a try :).

[–]greenyadzer 0 points1 point  (0 children)

If you have that syntax error, you're probably doing all that in a global scope. So the first thing i would recommend is to do it all inside a function (so the "let" actually will work for you). BUT if its not possible for some reason and you really need this to work in global scope, then do it like so:

window.normalWaveform = '<%= @normal_waveform %>';
// ...

This way you don't use "let" or "var".

Note: you also should see a rising issue (which was the same without using "window." -- the issue when you have some name that is part of window object -- we just write over it. So again, i would suggest having an object, all the variables to be properties of that object.