Function failed to pass the final results

Hello everyone,

I have passed all individual tests but when I run the final tests, I failed to pass the final results. What did I do wrong???

  **Your code so far**

const ret=[];
function steamrollArray(arr) {
for (let ele of arr){
if (Array.isArray(ele)){
  steamrollArray(ele);
}
else{
  ret.push(ele);
}}

return ret;
}

console.log(steamrollArray([1, [2], [3, [[4]]]]));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36

Challenge: Steamroller

Link to the challenge:

Your ret variable is in the global scope, meaning that it will be “polluted” with values from previous run.

You can easily see this by adding a new function call below your console.log

console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([[["a"]], [["b"]]]));

I can see logged in the console

[ 1, 2, 3, 4, 'a', 'b' ]

You should find a way for this to work with all the resources scoped to the function.
In general, you want to avoid global variables for this precise reason :slight_smile:

Hope this helps.

Hi Marmiz,

Thank you very much for your good enlightenment. I have found a way to run my code by simply add the ret as argument to the function and it is able to run successfully.

Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.