I was debugging some JavaScript and got super confused when my `console.log` statements were showing object properties that I thought shouldn't exist yet. What I learned is that when you log an object, most browsers don't take a snapshot immediately; they just keep a reference. So, by the time you expand the logged object in the developer tools, it might have mutated and show different values than expected. For instance, if I have `const obj = { a: 1 }; console.log(obj); obj.a = 2;` and then expand it, I see `a: 2` instead of `a: 1`. The fix is pretty straightforward: you can use either `console.log(JSON.stringify(obj));` or `console.log({ ...obj });`. Just wanted to share this in case it helps someone else who might run into the same headache!
5 Answers
What's interesting is that the order of the logs is maintained, but the expansion shows the live reference instead of the state at the time of logging. So effectively, the console evaluates the object when you expand it, showing you its current state.
Yep, this odd behavior tends to bite everyone who uses logging as a debugging tool. If you can anticipate that the object might change later, just stick with `JSON.stringify()` to capture the state when you log it.
The reason behind this is that the properties of the object aren't accessed until the logged object is expanded. You can use `console.dir` instead, which starts with the object already expanded.
A great tip in these situations is to use breakpoints and the `debugger;` statement. It's really helpful when you want to step through code and watch things happen in real-time.
This quirk can really mess with your debugging. JavaScript passes objects by reference, which means the logged object can change after you log it, especially when using async calls or promises!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically