While learning JavaScript, you likely learned about the powerful method .forEach() that allows us to process every element in an array separately. Now we will use a similar method that will enable us to process every row returned from a database query.

db.each("SELECT * FROM Dog WHERE breed = 'Labrador'", (error, row) => { // This gets called for every row our query returns console.log(`${row.name} is a good dog`); }, (error, numberOfRows) => { // This gets called after each of our rows have been processed console.log(`There were ${numberOfRows} good dogs`); });

In the code above we SELECT all the Labrador dogs from our Dog database. We offer affirmation to each of the animals individually and then announce how many received this praise in sum.

db.each() takes a query and a callback function that it performs on each row returned from the query. This is a useful technique for transforming or updating rows. This is also useful for memory management — we only have to look at one row at a time instead of trying to process every returned row at the same time. db.each() additionally takes an optional second callback function, which will be called when all of the queries are completed and processed.



Create an empty temperaturesByYear object before your query; we’ll use this to store temperature data for each year.


Inside a db.each() call, SELECT all the rows from TemperatureData.


In a callback from your db.each() call, add the temperature’s value to the temperaturesByYear. To do this, use the provided helper function addClimateRowToObject(row, object). The first argument is the row to add, the second argument is the object to add it to (temperaturesByYear in your case).


In the second callback to your db.each() call, create a final averageTemperatureByYear variable and set it equal to calling function calculateAverages with your temperaturesByYear object.


Log these averages using the given printQueryResults() function.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?