1

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.

Jeremy Jones
  • 4,561
  • 3
  • 16
  • 26
  • 2
    I hope the linked duplicate topics offer a solution and an explanation. However, I would recommend a different approach: instead of making the property names dynamic, just divide by `total` when *accessing* the map. – Bergi Apr 10 '20 at 14:44
  • Oops sorry posting a duplicate. Thank you. – Jeremy Jones Apr 10 '20 at 14:45
  • 1
    It doesn't work because it's JS syntax. If you want to use a string or any variable value as a key you need to use computed properties. Just wrap your key in [ ] braces. An example would be ["my crazy string key"]: "my value" – adam.k Apr 10 '20 at 14:45
  • No damage done, and I guess they're not easy to find :-) – Bergi Apr 10 '20 at 14:46
  • You'd say that in php, associative array but in JavaScript it's an object. ``` const encouragingMessages = { 100: "You've done 100! Well done!", 200: "You're half-way there! Good job!", 300: "Three-quarters done! Nearly finished!" }; let x = 200; ``` //let's suppose the number is 200 so it's only ``` encouragingMessages[`${x}`] //"You're half-way there! Good job!" ``` – Saadi Toumi Fouad Apr 10 '20 at 14:47

0 Answers0