Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand function return in javascript

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

Please help me.

like image 857
Md. Faridul Hassan Avatar asked Apr 09 '26 08:04

Md. Faridul Hassan


2 Answers

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);
like image 190
nicholaswmin Avatar answered Apr 10 '26 20:04

nicholaswmin


it's used to return a value from the function.

Let's say you want a function to do some calculation... for a simple example, like calculate a div box's left position on the browser screen.

you call the function and give it the html selector, then the function 'returns' you the left position value.

like image 26
Liquidchrome Avatar answered Apr 10 '26 20:04

Liquidchrome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!