First, functions and variables in Javascript are linked to a scope. In your second example your variable result
is linked to the document scope. Here is works, but consider this code:
function add(x,y){
result = x+y;
}
function alertAdd(x,y){
var result = add(x,y);
alert(result);
}
alertAdd(5,3);
If you run this, you'll get an alert with a value of 'Undefined' because the variable result
is defined in alertAdd
's scope. Meaning the main scope doesn't know about it and result
in your add()
function is not even defined in the first place. In other languages this would create an error.
Now consider this:
function add(x,y){
return x+y;
}
function alertAdd(x,y){
var result = add(x,y);
alert(result);
}
alertAdd(5,3);
This works because event if add()
and result
are not declared on the same scope, we ask add()
to return its value, not to assign it to a preexisting variable. Furthermore you could reuse add()
on any variable. Not only result
.
var result_b = add(1+2); // result_b = 3
var result_c = add(2+2); // result_c = 4
function logAdd(a,b) {
var value = add(a,b);
console.log(value);
}
logAdd(3,3); // 6