Arrow Functions

Arrow Functions

  • ES6 introduced/arrow function syntax/, a shorter way to write functions by using the special “fat arrow” (=>)

  • Instead, you first include the parameters inside the () and then add an arrow => that points to the function body surrounded in { } like this:

        const getArea = (width, height) => {
          const area = width * height
          return area
        }
    
        console.log(getArea(9, 8))
    
        
    

    JS Bin on jsbin.com


Parameter syntax rules for Arrow functions

  • Functions that take only a single parameter do not need that parameter to be enclosed in parentheses.

  • However, if a function takes zero or multiple parameters, parentheses are required

    • Zero parameters
        const functionName = () => {}
        
    
        const sayHello = () => { console.log("Hello") }
        
    
    • One parameter
        const functionName = param => {}
        
    
        const squareMe = num => {
          return num * num
        }
        
    
    • Two parameters
        const functionName = (paramOne, paramTwo) => {}
        
    
        const getArea = (width, height) => {
          return width * height
        }
        
    

Function body syntax rules for Arrow functions

  • A function body composed of a single-line block does not need curly braces or a return keyword

  • Without the curly braces, whatever that line evaluates will be automatically returned

  • This is referred to as implicit return

  • Examples

    • Single line block
          const squareMe = number => number * number
        
    
    • Multi-line block
          const verifyVotingEligibility = age => {
          	if (age > 18 ) {
              return true
            }  else {
              return false
            }
          }
        
    

Exercise

  • Convert the following function to an arrow function

  • Store the arrow function in a variable named areaOfCircle using const

  function areaOfCircle(radius){
    return Math.PI * (radius**2)
  }

JS Bin on jsbin.com