Anthony Eriksen
Anthony Eriksen

Reputation: 51

Question about functions and variables in JavaScript

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?

Upvotes: 1

Views: 64

Answers (1)

Steven Stark
Steven Stark

Reputation: 1259

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.

Upvotes: 2

Related Questions