Javascript challenge
Introduction
Today I took on a challenge from my Udemy course. The challenge was to average two football teams’ scores and log which team won the trophy.
Challenge Description
Challenge: Find the average.
There are two gymnastics teams: Dolphins and Koalas. They compete against each other 3 times. The winner with the highest average score wins a trophy!
Your tasks:
1. Calculate the average score for each team, using the test data included below. The average score for Dolphins should be assigned to the scoreDolphins
variable, and the average score of Koalas should be assigned to the scoreKoalas
variable.
2. Compare the team's average scores to determine the winner of the competition, and print to the console:
"Dolphins win the trophy"
if Dolphins win, or
"Koalas win the trophy"
if Koalas win, or
"Both win the trophy"
if their average scores are equal.
TEST DATA: Dolphins scored 96, 108, and 89. Koalas scored 88, 91, and 110.
My Approach
My first issue was not knowing how to average out scores. I searched Google and decided to use a For loop. I had not used a Function before and the search suggested I do. At first, I hard-coded the results of each team’s scores and then wrote my if/else code. It logged correctly, but when I asked chatgtp to check my work it caught that I had hard-coded the results. I did not realize that I could use the Function to average both out directly in the code like this:
let scoreDolphins = calculateAverage([96, 108, 89]);
let scoreKoalas = calculateAverage([88, 91, 110]);
My Code
function calculateAverage(scores) {
let sum = 0;
for (let i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum / scores.length;
}
let scoreDolphins = calculateAverage([96, 108, 89]);
let scoreKoalas = calculateAverage([88, 91, 110]);
if (scoreDolphins > scoreKoalas) {
console.log('Dolphins win the trophy.');
} else if (scoreKoalas > scoreDolphins) {
console.log('Koalas win the trophy');
} else {
console.log('Both win the trophy');
}
Lessons Learned
I learned that brackets are used in arrays to list items.
I learned that when you use a function you can reuse that function to complete multiple jobs.
I learned that there is usually an easier way to accomplish a task in Javascript (for example my hard-coding instead of using the Function).