1

Just wondering the difference in these 2 functions...

function getArea(width, height) {
  return width * height;
}




function getArea(width, height) {
  var area = width * height;
  return area;
}




I guess my question is, what is the point in the second example by storing the parameters in a variable?

2
  • 1
    "what is the point" ... there is none (in this case). Commented Mar 28, 2019 at 21:15
  • 1
    Generally, the reason to create a variable is to hold a value that will be needed more than one time. If it's a safe bet that that won't be the case, adding a variable just adds clutter. (IMHO). Commented Mar 28, 2019 at 21:18

1 Answer 1

2

The point to expanding your code this way would be for:

  • Code Readability. It's clearer in the second example as to what's going on because the variable acts as documentation in a way.
  • Debugging. In the 2nd example you can break on the return to see the value of area.
  • Code Style - many devs prefer one or the other for their own style.

On the other side, the benefit of not doing this would be:

  • The first example creates one less local variable, which is a smaller memory footprint.
  • Smaller line count. Some devs care about line counts and short code, not my thing, but to some it matters.
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh okay. Thanks for the side by side comparison and contrast!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.