Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JavaScript logging it "0"?

Tags:

javascript

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);
like image 680
Nipun Garg Avatar asked Dec 06 '25 17:12

Nipun Garg


2 Answers

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);
like image 123
Zakaria Acharki Avatar answered Dec 09 '25 16:12

Zakaria Acharki


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);
like image 41
AmericanUmlaut Avatar answered Dec 09 '25 16:12

AmericanUmlaut