1

I am confused what the difference is between mine and the 'correct way'. I get my way is wrong scope but how did it result the way it did? I am not understanding how the result came out.

Here is the function:

convertObjectToList({
    name: 'Holly',
    age: 35,
    role: 'producer'
});

Desired answer: [['name', 'Holly'], ['age', 35], ['role', 'producer']]

My way:

function convertObjectToList(obj) {
    var brackOut = [];
    var brackIn = [];

    for (let key in obj) {
        brackIn.push(key);
        brackIn.push(obj[key]);
        brackOut.push(brackIn);
    }

    return brackOut;
}

convertObjectToList({
    name: 'Holly',
    age: 35,
    role: 'producer'
});

Result:

[ [ 'name', 'Holly', 'age', 35, 'role', 'producer' ],
  [ 'name', 'Holly', 'age', 35, 'role', 'producer' ],
  [ 'name', 'Holly', 'age', 35, 'role', 'producer' ] ]

vs.

The 'correct way':

function convertObjectToList(obj) {
    var brackOut = [];

    for (let key in obj) {
        var brackIn = [];

        brackIn.push(key);
        brackIn.push(obj[key]);
        brackOut.push(brackIn);
    }

    return brackOut;
}

convertObjectToList({
    name: 'Holly',
    age: 35,
    role: 'producer'
})

Result: [ [ 'name', 'Holly' ], [ 'age', 35 ], [ 'role', 'producer' ] ]

It has to do with the scope of variable, but can someone explain how my answer got that way? How does this work?

talemyn
  • 7,822
  • 4
  • 31
  • 52
dekim2324
  • 15
  • 5

1 Answers1

2

Actually brackIn has the same scope in both cases¹. What matters is that you assign a new array to brackIn inside of the loop:

 var brackIn;

 for(let key in obj) {
   brackIn = []; // <<< !!!
   //...
 }

In the "wrong version", you always push to the same array and you also push that array to brackOut on every iteration (pushing the array won't clone it, JS has call by sharing).

¹: Cause var is always scoped to functions (so your code is equal to the excerpt above). If you'd use let you would scope the variable locally to the loop.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151