I'm learning javascript; I'm confused about when to use 'return.' So far I know 'return' is used either to specify exactly what value to return or to stop a function from running.
But, when comparing my solution to the answer key, its function required a return statement, but mine did not. Yet, both displayed the same results on the console. Why? Are the results actually different?
Problem: "Using a WHILE loop, calculate the percentage of students' test scores stored in the testScore array. The test has a total of 50. Store the percentages in another array and display it to the console."
My Solution:
const testScore = [10, 40, 30, 25];
const percentages = [];
const gradePercentage = (scores) => {
const perc = (scores / 50) * 100;
percentages.push(perc);
};
let i = 0;
while (i < testScore.length) {
gradePercentage(testScore[i]);
i++;
}
console.log(percentages);
Answer Key
const testScore = [10, 40, 30, 25];
const percentages = [];
const gradePercentage = (scores) => {
return (scores / 50) * 100;
};
let i = 0;
while (i < testScore.length) {
const perc = gradePercentage(testScore[i]);
percentages.push(perc);
i++;
}
console.log(percentages);
Both displayed this result: