Return confusion


Joined
Feb 15, 2021
Messages
7
Reaction score
0
Hi,

i am having trouble understanding the "return" concept (i am at the very beginning.... so please go slow and explain everything... coming from a newbie perspective)

first, what is a return?

how is a return determined?

what does a return do for me?

anything else i should know?

kindly provide code examples involving returns

MANY THANKS!
 
Ad

Advertisements

Joined
Feb 15, 2021
Messages
7
Reaction score
0
thanks!

i followed the link and have follow up questions :)

Code:
function square(x) {
   return x * x;
}
var demo = square(3);
// demo will equal 9

When a return statement is used in a function body, the execution of the function is stopped.

got it!

If specified, a given value is returned to the function caller. not so much

is my
Code:
var demo = square(3)
; my function caller?

what does "a given value is returned to the function caller" accomplish?

maybe provide a few real examples?

could my function caller look different?

could my return be anything?

say return
Code:
x + 10
(random thought)

i guess my question is how a return is made the way it is made. i hope that makes sense!

seriously, thank you for your time and guidance!

tricky one for me!
 
Ad

Advertisements

Joined
Jul 12, 2020
Messages
20
Reaction score
2
The 'return' stop a functions processing, but can return information to the 'caller'. In your example:
Code:
function square(x) {
   return x * x;
}
var demo = square(3);
// demo will equal 9

The function is returning the value of 3 x 3 which is 9. If you changed the function to read:
Code:
function square(x) {
   return;
  var x = x * x;
  return x;
}
var demo = square(3);
// demo will equal 9
It will return nothing. Here the use of the first 'return' statement tells the script not to do anything but return to the caller, so the rest will not be executed. Another thing is, in your example the variable is being set by the 'call' to the square function. You can just as easily call the function
Code:
function square(x) {
 if( x < 5){ return; }
else {
  var x = x * x;
  alert( x);
}
}

square(3);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top