...

Dynamic Array Access

So far, we've accessed array elements using literal numbers like colors[0] or colors[2]. But you can use any expression that evaluates to a number as an index.

This means you can use variables as indexes too:

let planets = ["Mercury", "Venus", "Earth"];
let position = 1;
console.log(planets[position]);  // "Venus"

This makes arrays incredibly powerful, as you can access different elements based on user input, calculations, or other dynamic values.

Your Task

Ask the user for a planet number from 1 to 8.

Print the planet at position index - 1 (remember, arrays start at 0, so planet #1 is at index 0).

Variables

No variables

Loading...

Output (Console)