Question on Piano Keys

// The keys and notes variables store the piano keys

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 = ;

keys.forEach(function(key){

notes.push(document.getElementById(key));

})

// Write a loop that runs the array elements through the function

notes.forEach(note => motion(note))

Hi, I wonder how does the forEach() function help with making the program works. Thanks a lot!

Link to the project: https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-building-interactive-websites/modules/wdcp-22-dom-events-with-javascript/projects/piano-keys

You need an notes to be an array of html elements.
You already have the ids in the array keys.
So you would loop though the array of ids (which is keys), get the element with that id, and add it to the notes array.

doing that only for 'c-key' would look like this:

  notes.push(document.getElementById('c-key');

but you want to do that for all the ids (strings) in the array keys, so a loop is needed:

for (let key of keys) {
  notes.push(document.getElementById(key);
}

or you could do that using function:

function stuffToDoForEach(key) {
  keynotes.push(document.getElementById(key);
}

for (let key of keys) {
  stuffToDoForEach(key);
}

which can be written using the for-each method for the keys array:

keys.forEach( function(key) {
    notes.push(document.getElementById(key));
  } // end of function
);

Each element must have an event listener attached to it so that something happens when a user clicks on it. (That would use a function that indicates what we want to happen when a user clicks on that HTML element.)
You could have a function that will add the event listeners to an HTML element.
But you need to an identical event listener to every element in the notes array.
You’d use a loop for that,
and could do that loop using notes.forEach

Here’s a simple example of using .forEach for an array:

const list = [1, 5, 9, 13]; list.forEach( function(item) { console.log(item); } // end of function );

Remember that function that’s being used as an argument for .forEach
will run using each element in the array as an argument for the function, one at a time.

1 Like

Hi, jan. Really appreciate your detailed explanantion :+1: