Odd (to me) behavior of JS objects and console.log()

I am unsure why console.log() prints out the final value of the object, instead of printing out the current state of the object as I log them to the console. I create an object, then console.log() it. Then I call a function (func1) to mutate object.a, then console.log() it. Again with func2 to mutate object.a and then log it. However, console.log() has the same output...? I hope that makes sense, any help would be appreciated. Thanks 🙂
8 Replies
garethmoore.
garethmoore.•3y ago
Stack Overflow
When does console.log get executed?
I'm trying to debug some pretty simple Javascript using console.log, but it's outputting values for variables that are not changed until after the console.log call, when the variables are 'class' m...
garethmoore.
garethmoore.•3y ago
Apparently, when you expand the console.log() log it opens with the latest object and not as the object was when the console.log() was executed. If you instead use the spread operator to unpack the object you will get the desired outcome.
Jochem
Jochem•3y ago
as a note: It's generally a bad idea to have functions with side effects like you do here. If it's just to demonstrate the behavior, that's fine, but it's not a good idea anywhere else
garethmoore.
garethmoore.•3y ago
Thanks for your answer Jochem, just a little unsure what you mean? Functions with side effects? Are you happy to clarify that for my caveman brain?
Jochem
Jochem•3y ago
side effects in this context are changes to the application state done inside the function. You're calling a function, and that changes a variable with a specific name outside the function. It's clear now because everything fits on 11 lines of code, but if that function is somewhere else, it gets really hard to reason about what it's doing also, those functions are now only usable if you have a global scope variable called object with a key a that's an array the better way to do something like that is to have the function take as arguments the data it needs to work, then return the modified data and reassign it I'd suggest reading up on functions with side-effects online, it'll help your code quality in general
garethmoore.
garethmoore.•3y ago
Thanks for your clarification Jochem, I've tried this, do you mind letting me know if I'm on the right track.
garethmoore.
garethmoore.•3y ago
Also thanks for the heads up. I'll add functions with side-effects to my to do list today 🙂
Jochem
Jochem•3y ago
you could simplify that and just drop the function altogether object.a[0] = 9; would have the same result 🙂
Want results from more Discord servers?
Add your server