Why does JavaScript register it "0"?
This code registers the output as zero. The 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);
source to share
You have to use the keyword var
when declaring r
localy variable inside fucntion else, you will have a scope conflict, and r
inside the function it will be declared globaly and will be considered the same variable with the variable r
outside the function:
function sum(a,b){
var r=a+b;
return r;
}
Hope it 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);
source to share
When declaring variables, you need to use var
. 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 the following:
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);
source to share
This is because you didn't declare the r variable inside
with the var key. Thus, it is in the global scope.
When you do this r1 = sum (1,4) the r value is redefined to
5, and r1 is also 5. Unlike r-r1 revolutions
out to 0.
To avoid this, you can use the var keyword to declare r inside a function.
function sum(a,b){
var r=a+b;
return r;
}
r=sum(2,9);
r1=sum(1,4);
diff=r-r1;
console.log(diff);
This will help.
source to share