I don't understand function return in javascript -


can explain why javascript return statement used in function? when , why should use it?

please me.

why used in function?

1. return results of function

the return says - returns values function caller

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

2. stop execution of function

another reason return used because breaks execution of function - means if hit return, function stops running code follows it.

function sum(num1, num2) {    // if of 2 required arguments missing, return false    if (!num1 || !num1) {      return false;    }     // , not continue following     var result = number1 + number2;    return result; }  var result = sum(5); // sum() returned false because not arguments provided 

why should use it?

because allows reuse code

imagine you're writing application geometric calculations - along way might need calculate... e.g the distance between 2 points - common calculation.

  • would write formula again each time need it?
  • what if formula wrong? visit all places in code formula written make changes?

no - instead wrap function , have return result - write formula once , reuse everywhere want to.

function getlinedistance(x1, y1, x2, y2) {     var distance = math.sqrt((math.pow((x2 - x1), 2)) + (math.pow(( y2 - y1), 2)));     return distance; }  var linedistance1 = getlinedistance(5, 5, 10, 20);  var linedistance2 = getlinedistance(3, 5, 12, 24); 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -