Home > Mobile >  Is the function with return or without better in JavaScript?
Is the function with return or without better in JavaScript?

Time:07-14

I am new at coding and I am currently learning about the return statement. consequently I am coded two functions, one without the return tool and one with the return statement whereby the two functions are doing the same thing. The functions are calculating after users input the price for the route. For my programming development I want to now which of these functions are better to use, the function with return or the function without. Thank you.

function calculatingExpenses() {
  let km = prompt("How far is your target");
  let partialExpenses = 1.65;
  const wholeExpenses = km *= partialExpenses;
  console.log(wholeExpenses);
}
function wholeFunction() {
    function calculatingExpenses(km) {
      return km * 1.65;
    }
    const km = prompt("How far is your target?");
    const wholeExpenses = calculatingExpenses(km);
    console.log(wholeExpenses);
}
  

CodePudding user response:

Both work just fine, although technically your first function is slightly more optimized because your second function entails adding an additional function call frame to the call stack making it ever so slightly slower.

CodePudding user response:

It is a good idea to limit each function to one responsibility.

Also, try to make the functions without side effects.

I would re-write your code like this: (but this is becoming an opinionated question/answer)

function calculatingExpenses(km) {
  return km * 1.65;
}

function main() {
  let km = prompt("How far is your target");
  let result = calculatingExpenses(km)
  console.log(result);
}

main();

  • Related