0

I am a rookie practicing on some javascript. In one of the challenges, I plan to get an array of **[nav1, nav2, ...nav5]** using template string method to declare the variable (**'nav'+i**). Below codes gave me an error of "*Uncaught SyntaxError: Invalid left-hand side in assignment*".

What is the solution here? Please give me your advice and appreciate your time. / Thanks

const navItems = [];
for (let i=1; i<6; i++) {
    `nav${i}` = document.getElementById(`nav-${i}`);
    navItems.push(`nav${i}`);
}
Chuong
  • 1
  • 2
  • JavaScript has no concept of dynamic variable naming, and you should not try to implement such a feature. Use objects instead. – Teemu Mar 08 '21 at 16:40
  • Why do you even need variables here? ``const navItems = [1,2,3,4,5].map(i => document.getElementById(`nav-${i}`));`` – Heretic Monkey Mar 08 '21 at 16:41
  • Big thanks @HereticMonkey !!! so simple! but i did complicate myself – Chuong Mar 08 '21 at 16:45
  • Beginners often want to do this kind of thing. An `id` identifies a unique element, and obviously you have more than one nav element since you suffix them with a number and you treat them as a collection. It's the wrong tool for the job. Use a `class` instead. Typically `const navItems = Array.from(document.querySelectorAll('.nav'))` will do what you need. You may not even need to convert the NodeList to an Array depending on your use case. — Try to ask about use cases and not about solutions to use cases. – geoffrey Mar 08 '21 at 17:13
  • Thanks @geoffrey , great advice for a rookie mistake. – Chuong Mar 08 '21 at 18:25

0 Answers0