An array holding objects with names that are equal to my html id's is selecting those id's

I made an array called colors and it holds these values : [green, blue, yellow, red]. I did not make html selectors for the values in colors to select my html, but when I see the values of the array in my console it shows the values in colors are selecting html elements with the same id names, but I never used a javascript html selecting method to do this. I don’t know why this is happening, but I don’t want to undo it since it will shorten my code. Is this something javascript does automatically, or is it something that is done by the browser, why is this happening?

here is my code with the array :

  let game = {
    on : false,
    start : false,
    strict : false,
    score : 0,
    computerMoves : [],
    playerMoves : [],
    colors : [green, blue, yellow, red]
  }
  

and a link to a codepen of my project : https://codepen.io/icewizard/pen/JLBpNQ

Maybe the imported js file (simon.js) has the same variable names?

I didn’t see any initialisation of the colours variables. So maybe it is from the imported file.

the simon.js file is the same file as the one shown in code pen. I’m working on an ide and copy/pasting the code to codepen to share it. the only time I mentioned the green, blue, yellow and red is in the colors array I made. I want to know why this is happening because if its a bug then I will hardcode the html selectors in.

Yup, you’re right. Weird. I tested on my own pen and same thing happened. Same as your pen, I didn’t initialise the variables.

Maybe Javascript has such a function. Or CodePen has such a function.

If I set the initialisation, the console.log shows as it should be.

You can refer to html elements which have an id simply by referencing their name as a variable in JavaScript. The catch is the id names can only be alphanumeric.

1 Like