Functions Calling Other Functions

Functions can call other functions

  • Function reusability is key results in cleaner code

  • Reusing functions leverages key programming principle - Don’t Repeat Yourself (DRY)


Example

  • In the example of below, the surfaceAreaOfCube function calls another function (areaOfSquare) instead of duplicating work that was already done
// Function that calculates area of a square

function areaOfSquare(side){
  return side * side
}

areaOfSquare(3) // returns 9


// This is a function that calculates the
// surface area of a cube that *reuses* the areaOfSquare function

function surfaceAreaOfCube(side){
  return 6 * areaOfSquare(side)
}

surfaceAreaOfCube(7) // returns 294

JS Bin on jsbin.com


Exercise

  • Create a function named surfaceAreaOfSphere that calculates the surface area of the Sphere using the following formula: 4 * PI * r**2; the function MUST reuse the provided areaOfCircle function

JS Bin on jsbin.com