I'm maintaining a bit of Javascript code that uses an associative array to store progress messages, something like this:
const encouragingMessages = {
100: "You've done 100! Well done!",
200: "You're half-way there! Good job!",
300: "Three-quarters done! Nearly finished!"
};
I know that keys are strings, not integers, but my issue is that I want those numbers to be controllable depending on the total, something more like this:
const encouragingMessages = {
`${parseInt(total / 4)}`: `You've done ${parseInt(total / 4)}! Well done!`,
`${parseInt(total / 2)}`: "You're half-way there! Good job!",
`${parseInt(total * .75)}`: "Three-quarters done! Nearly finished!"
};
But although using raw integers works ok, trying to use an interpolated string doesn't work, even when including letters, and using toString()
:
`foo${parseInt(100).toString()}`: 'bar',
Results in Parsing error: Unexpected token
.
Aren't these strings still strings, and usable as keys? I know that using raw integers themselves is probably bad practice, but my understanding is that these keys are strings:
> typeof `foo${parseInt(100)}`;
'string'
and would (I thought) therefore be usable as keys in this situation.
I'll probably just change this altogether to something clearer, but for my own understanding & to avoid wasting time in future I'd appreciate any clarification on why this doesn't work.