+ 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?
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
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()"
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
0
Thanks
0
function addNumbers(a, b) {
var c = a+b;
return c
}
document.write(addNumbers(40, 2));
0
when I remove the C I get an undefined.
0
does that work ?
0
Do by saying Return C then you are making the value available outside of the function (global scope)
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
0
Yes @Johnny, to make things short addNumbers call will be replaced by the value of c
0
Thanks everyone I think I get it now =D
0
You are welcome ! :)