This code logs the output to be zero. Output should be 6.
function sum(a,b){
r=a+b;
return r;
}
r=sum(2,9);
r1=sum(1,4);
diff=r-r1;
console.log(diff);
You've to use var keyword when you declare the r variable localy inside the fucntion else you'll have a scope conflict and the r inside the function will be declared globaly and considered as the same variable with the r variable outside the function :
function sum(a,b){
var r=a+b;
return r;
}
Hope this helps.
function sum(a,b){
var r=a+b;
return r;
}
r=sum(2,9);
r1=sum(1,4);
diff=r-r1;
console.log(diff);
You need to use var when declaring variables. By not using var you are implicitly creating global variables.
function sum(a,b){
r=a+b; // This ends up being a reference to the same `r` as below
return r;
}
r=sum(2,9); // This creates a global variable called r and sets it to 11
r1=sum(1,4); // This sets global `r` to 5 (because of the r=a+b in sum()
diff=r-r1; // 5 - 5 is 0
console.log(diff);
Instead do this:
function sum(a,b){
var r=a+b; // Now this r is local to the sum() function
return r;
}
var r=sum(2,9); // Now this r is local to whatever scope you are in
var r1=sum(1,4);
var diff=r-r1;
console.log(diff);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With