0

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:

enter image description here

chickpea
  • 79
  • 8
  • 1
    The *implicit return value* of your arrow function is the result of evaluating the last statement. `Array#push` returns the result of pushing the item, so the value you're seeing matches returning the array explicitly. – D M May 18 '22 at 18:17
  • More: [Returning a value without an explicit return statement](/questions/16895683/returning-a-value-without-an-explicit-return-statement), [When should I use a return statement in ES6 arrow functions](/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions), [Does every Javascript function have to return a value?](/questions/17337064/does-every-javascript-function-have-to-return-a-value) – D M May 18 '22 at 18:21

1 Answers1

2

When you run your function, you directly mutate percentages by calling percentages.push(perc);, while the answer key's gradePercentage function does not mutate percentages.

The answer key does what is called pure function, a deterministic function which has no side effects. Personally, I prefer to write this sort of functions, since they can be easily tested.

Lior Pollak
  • 3,362
  • 5
  • 27
  • 48