+ 2

Why use a return value?

if var c = a+b then why do I need to say Return C. The value of c is already held in the variable?

15th Jul 2017, 8:03 PM
John Hay
John Hay - avatar
12 Answers
+ 3
Wherever you write "var c" (define the variable) is where the variable gets stored. If you define it outside of any functions, then the variable can be accessed and modified from anywhere (it is called a "global" variable). So, instead of using return, you could write: var c; function sum(a, b){ c = a + b; } sum(5, 9); //Now c has a value of 14; If you first write "var c" inside the function, you will not be able to access it outside of the function; so you use "return" to have the value of c outputted by the function. "return" will not make it a variable, but will in a way give the function a value of c which you can assign to another variable. function sum(a, b){ var c = a + b; return c; } var fourteen = sum(5, 9); var fifteen = sum(5, 10); //Now fourteen has the value 14 //fifteen has a value of 15
16th Jul 2017, 12:32 AM
James
James - avatar
0
The function that you have that code in, Is it in a custom function like is it int Function(var c) or something ? If so, change "int Function" to "void Function" or "Function MyFunction()"
15th Jul 2017, 8:07 PM
Dillion Piazza
Dillion  Piazza - avatar
0
It is held in the variable INSIDE the function. This c variable has meaning only in the function's scope, not in a global scale, so if you do not return c, its value will be lose at the end of the function call. Try to remove the return, you should have an "Undefined c" or something like that if you did not declared another variable named c outside of the function
15th Jul 2017, 8:08 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
Thanks
15th Jul 2017, 8:15 PM
John Hay
John Hay - avatar
0
function addNumbers(a, b) { var c = a+b; return c } document.write(addNumbers(40, 2));
15th Jul 2017, 8:15 PM
John Hay
John Hay - avatar
0
when I remove the C I get an undefined.
15th Jul 2017, 8:15 PM
John Hay
John Hay - avatar
0
does that work ?
15th Jul 2017, 8:16 PM
Dillion Piazza
Dillion  Piazza - avatar
0
Do by saying Return C then you are making the value available outside of the function (global scope)
15th Jul 2017, 8:17 PM
John Hay
John Hay - avatar
0
c = a + b but if you want to use c in other functions you have to return it then every time you call your function in others functions , you can have the value of c
15th Jul 2017, 8:18 PM
Shervin Jarrahi
Shervin Jarrahi - avatar
0
Yes @Johnny, to make things short addNumbers call will be replaced by the value of c
15th Jul 2017, 8:18 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
Thanks everyone I think I get it now =D
15th Jul 2017, 8:45 PM
John Hay
John Hay - avatar
0
You are welcome ! :)
15th Jul 2017, 9:16 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar