I am sort of new to Javascript and wanting to clear something up, I have read something about Hoisting and feel this might be the reason and answer to my question but why does the log, log out the last assignment to my constant ?
const people = [
{
name: "Roger",
age: 29,
role: "Secret Agent"
},
{
name: "Jamie",
age: 35,
role: "Secret Agent"
}
]
console.log("people", people);
people[0].name = 'bob';
console.log("people", people);
Both results display bob and not Roger then Bob.
It would be great if somebody could explain why this happens.
This is an implementation quirk. Chrome (V8) and Firefox (SpiderMonkey) will resolve to the object at the time you expand the object in the console. Behind the scenes, the value might have changed. WebKit (Safari) will log it as it is. If you want to capture the object as it is at a certain point in time, use console.log(JSON.parse(JSON.stringify(obj)));
[1] https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Logging_objects
P.S Javascript is littered with these kinds of quirks. Not to discourage you, but what should be is quite frequently not what it is. This example also draws close parallels to asynchronous programming in javascript which can be jarring to those coming from procedural backgrounds. To oversimplify, your value will change behind the scenes before you reach the next line and thus it's a good idea to understand the event loop, callbacks and subsequently promises and async/await.
Please look at this question: console.log() shows the changed value of a variable before the value actually changes. This is a bug that only happens with console.log
. Unless you are relying on console logging for what you are trying to create, this shouldn't be a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With