Javascript developers, rely on console.log function to print out information on the console, often used for quick debugging. However, the console.log function isn’t as reliable as it seems.
Take a look at this Object printed from the console:
This is just an object containing a foo
key with the value bar
. However, take a look at the the white i inside a blue background next to bar
When you hover over this icon, you will see the text “The value was evaluated just now”
What this means is that the value of the object’s information was retrieved at the moment you clicked on the dropdown arrow.
Why is this important? What if another variable tried to access that value?
Lets look at the following example
var y = { data:{} };
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
y.data = json;
// console.log(json);
})
console.log(y);
The console.log printing us the value of y, gives us the following
data: {userId: 1, id: 1, title: "delectus aut autem", completed: false}
Everything appears normal, until we want to print out a single element from our object
var y = { data:{} };
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
y.data = json;
});
console.log(y.data.title);
When we print y.data.title, it returns undefined. This is because the browser calculates the value of objects in real time, and not the value at the moment at which console.log called y.data.title
If you’re familiar with promises, you would want to change and modify the we added from within the arrow function of our our fetch function’s second `.then` method.
However, when codebases get very large it is easy to see something print in the console and assume that its ready for us to use manipulate, duplicate and pass into other functions.
For a more reliable way to test your code I would recommend using breakpoints.