I don't understand function return in javascript

前端 未结 3 1212
日久生厌
日久生厌 2021-01-15 08:20

Can anyone explain why javascript return statement is used in function? when and why we should use it?

Please help me.

3条回答
  •  臣服心动
    2021-01-15 09:06

    Why is it used in a function?

    1. To return back the results of the function

    The return does what is says - it returns back some values to the function caller

    function sum(num1, num2) {
      var result = number1 + number2
    
      return result
    }
    
    var result = sum(5, 6) // result now holds value '11'
    

    2. To stop the execution of the function

    Another reason that return is used is because it also breaks the execution of the function - that means that if you hit return, the function stops running any code that follows it.

    function sum(num1, num2) {
      // if any of the 2 required arguments is missing, stop
      if (!num1 || !num1) {
        return
      }
    
      // and do not continue the following
    
      return number1 + number2
    }
    
    var result = sum(5) // sum() returned false because not all arguments were provided
    

    Why we should use it?

    Because it allows you to reuse code.

    If for example you're writing an application that does geometric calculations, along the way you might need to calculate a distance between 2 points; which is a common calculation.

    • Would you write the formula again each time you need it?
    • What if your formula was wrong? Would you visit all the places in the code where the formula was written to make the changes?

    No - instead you would wrap it into a function and have it return back the result - so you write the formula once and you reuse it everywhere you want to:

    function getLineDistance(x1, y1, x2, y2) {
      return Math.sqrt((Math.pow((x2 - x1), 2)) + (Math.pow(( y2 - y1), 2)))
    }
    
    var lineDistance1 = getLineDistance(5, 5, 10, 20); 
    var lineDistance2 = getLineDistance(3, 5, 12, 24);
    

提交回复
热议问题