1

I was trying to read all the values in a map/jsonobject. Following is my function call,

a ={"a":{"b":"c"}}
result= test(a,'a')    
console.log(result)

And the function is,

function test(jsonObj,name){

    main = ""
    if(jQuery.type(jsonObj)==='object'){
        $.each(Object.keys(jsonObj),function(){
             main += test(jsonObj[this],name+'_'+this)  
        });
   }else{
       main +=jsonObj;
   }   
   return main
}

When I execute the above script I am getting an ouput c.

Later I modified the function a little,

function test(jsonObj,name){        
    main = ""
    if(jQuery.type(jsonObj)==='object'){
        $.each(Object.keys(jsonObj),function(){
            resp = test(jsonObj[this],name+'_'+this) //this line added
            main +=resp
        });
   }else{
       main +=jsonObj;
   }   
   return main
}

Now I am getting cccc as my output. I am not able to understand the behaviour. Why am I getting different(unexpected) result when I introduced a new variable?

Kajal
  • 709
  • 8
  • 27
  • in our old code you are calling test function again and main = " " reset the variable value. in second code main variable is just appended with resp variable so u are getting cccc as our output – Chaitanya Ghule Aug 19 '17 at 12:46
  • just add console.log(main) in your $.each function and debug the code u will come to know the difference between the two o/p's – Chaitanya Ghule Aug 19 '17 at 12:47
  • In my first code I am not initialling the main inside the loop. I am just appending – Kajal Aug 19 '17 at 13:23

1 Answers1

1

Your variable main is declared in global scope. Because of that, the recursion in the function just adds new results to it.

By declaring your variable with var keyword, you limit its scope to the function

function test(jsonObj, name) {        
    var main = "";
    if (jQuery.type(jsonObj)==='object') {
        $.each(Object.keys(jsonObj),function() {
            resp = test(jsonObj[this],name+'_'+this); //this line added
            main +=resp;
        });
    } else {
        main +=jsonObj;
    }
    return main;
};

a ={"a":{"b":"c"}};
result= test(a,'a');    
console.log(result); // outputs 'c'

I've also fixed some small typos in your code, such as missing semicolons etc.

Petr Cibulka
  • 2,452
  • 4
  • 28
  • 45
  • Thank you Petr. Adding Var to the variable main solved my problem. – Kajal Aug 19 '17 at 13:22
  • In the first and second the scope of `main` remains the same. Then why we get different output? It will be great if you explain me in bit more details? – Kajal Aug 19 '17 at 13:24
  • I accept your answer later, so that someone else may be interested to provide more info on this thread. – Kajal Aug 19 '17 at 13:25
  • Checkout this answer for more info on `var` keyword: https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-to-use-it-or-omit-it – Petr Cibulka Aug 19 '17 at 14:04