1
votes

I'm trying to understand why I'm able to push the key into var attempt in the higher order function but result stays at 0 and isn't increasing.

function arrayBuilder(obj) {
let count=0
let result=0
let attempt=[]
for(let currentkey in obj)
{
  count=obj[currentkey]
  var hello=getValues(count,currentkey,result,attempt)
  
}


 console.log(attempt);
 console.log(result);
 return attempt;
}

function getValues(counting,key,result,attempt)
    {
  
  
  // for loop and push into result
  for(let i=0;i<counting;i++)
    {
        attempt.push(key)
        result++
        
        
      
    }
}
 
 console.log(arrayBuilder({'cats': 2, 'dogs': 1})); // => ['cats', 'cats', 'dogs']
 console.log(arrayBuilder({})); // => []
The number parameter result in your getValues function is not a reference to the variable result in arrayBuilder. Consider them two different independent variables, with the same values. So updating one doesn't update the other. This is totally opposite for attempt, which is an array so it is passed by reference, so you get the same array inside getValues. - James
pass by reference vs pass by value. stackoverflow.com/questions/518000/… - epascarello