Lodash project - question about declaring variables in loops?

If you declare the variable originalValue inside the loop using let originalValue = object[key]; instead of how its done in the image, the code doesn’t seem to work. Yet in other instances, you can declare variables in loops. How comes you can’t this time?

you can declare variables in loops

Yes, but it’s probably not what you’re thinking:

var list = [1,2]
for (const x of Array(5).keys()){
	list[x] = 3
	console.log(list);
};
/* output:
[ 3, 2 ]
[ 3, 3 ]
[ 3, 3, 3 ]
[ 3, 3, 3, 3 ]
[ 3, 3, 3, 3, 3 ]
*/
console.log(list[3])
// outputs: 3

In this is example if you just say list = x, it will change values in every iteration but it won’t retain them.

One more example:

var list = [1,2]
for (const x of Array(5).keys()){
	list[x] = x
	console.log(list);
};
/* output:
[ 0, 2 ]
[ 0, 1 ]
[ 0, 1, 2 ]
[ 0, 1, 2, 3 ]
[ 0, 1, 2, 3, 4 ]
*/

Thanks a lot, I think I get what you’re saying. But in let originalValue = object[key] ; won’t the key be different each time as you work through the object so you’re not reassigning are you?

E.g. If I had invert{propertycats: pink, propertydog: blue} if would become:

  1. let invertedObject = {};
    let originalValue;
    for (let key in object) {
    originalValue = object[key]; //original value = pink
    invertedObject[originalValue] = key; // inverted Object now has a property called pink with a value of propertycats.
    }

let originalValue;
for (let key in object) {
originalValue = object[key]; //original value = blue
invertedObject[originalValue] = key; // inverted Object now has a property called blue with a value of propertydogs.
}

So my question is , why would they be reassigned when the property and values being added to invertedObject is changing? it’s not like invertedObject is reassigning the same property each time?

I don’t quite understand your examples as I haven’t learnt about const x of yet. :frowning:

Sorry, the for loop in my example is just generating a generic loop of numbers. Nothing fancier than that :slight_smile:

for (const x of Array(5).keys()){

	console.log(x);
};
/*output
0
1
2
3
4
*/

If you declare the variable originalValue inside the loop using let originalValue = object[key] ;

Notice in my examples I did’t declare list before-hand. You should play around with what happens if you do. My only idea in giving you these is that if you play around with these, you might be able to find the answer you’re looking for and more!

Whenever you’re unsure as to what a loop does, the best thing to do is to get your hands dirty and see what’s going on. You have a lot of changing variables key, originalValue, object[key], invertedObject[originalValue]. If you log them at each juncture: x is y now, x is z now etc… you will have a better idea of why it ‘works’ one way and not the other.

1 Like