Piano Keys


Could someone explain how the following ‘forEach’ code works?

const keys = [‘c-key’, ‘d-key’, ‘e-key’, ‘f-key’, ‘g-key’, ‘a-key’, ‘b-key’, ‘high-c-key’, ‘c-sharp-key’, ‘d-sharp-key’, ‘f-sharp-key’, ‘g-sharp-key’, ‘a-sharp-key’];
const notes = ;

Firstly, I cannot find ‘key’ id in the HTML file. All ids are ‘x-key’ such as ‘c-key’, ‘d-key’ etc.
I understand forEach method applies callback function to each element of an array.
I don’t understand how this code links each element on ‘keys’ array to HTML element?
Would this be the same if I manually write “const notes =[document.getElementById(‘c-key’) … docment.getElementById(‘a-sharp-key’)]”?


1 Like

Well, key might just have been replaced by x or any word to your liking. Key is just used as a name because that would make sense in the context for readability purposes.

What the forEach function does is check each item of an array, in this case the array of keys. And use it as an input parameter for a function or method. In this particular exercise you want to get each key to access its counterpart in the Dom and push them to a new array notes so that we can do some magic!

And yes that would be exactly as you suggested. So you are thinking the right way ;).

1 Like

Thanks, again! Sorry for late reply.
I was stupid I was looking for id=“key.” But realised there is no quotation mark in parentheses of getElementById. Now I understand element (=key) is passed into the parentheses of getElementById.

1 Like