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
Minutes after posting this I ran into https://stackoverflow.com/questions/13218273/when-does-console-log-get-executed
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...
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.
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
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?
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 generalThanks for your clarification Jochem, I've tried this, do you mind letting me know if I'm on the right track.
Also thanks for the heads up. I'll add functions with side-effects to my to do list today 🙂
you could simplify that and just drop the function altogether
object.a[0] = 9;
would have the same result 🙂