Hello All,
I’m confused about how console.log is used. I have googled it and read about it, but I am still wondering why sometimes we console.log inside what I think we call the local scope, such as inside a for loop or a function, yet other times we need to console.log in what I think we call the global scope which is outside of a for loop or function. I am not understanding when you console.log either globally over locally. Can someone please explain it? Thank you!
Hmm in simple terms…
console.log inside a for loop or a function would be to check if things are working within the loop before getting the the end result.
console.log in a global scope would be to check if the end result of a function or if the value of a function is what you wanted.
That’s the way I see it.
Thank you, that makes sense. It seems easy enough but for some reason I found the whole thing confusing. Thanks for the help!
Yep as @Josue said - Use console.log()
locally when you want to inspect or debug something that only exists in that specific scope (like a function or loop). Use it globally when you need to check values that exist throughout the whole program.
// local scope logging
for (let i = 0; i < 5; i++) {
console.log(i); // Logs 0, 1, 2, 3, 4 inside the loop's local scope
}
// global scope logging
let total = 0;
function addValue(value) {
total += value;
}
addValue(10);
console.log(total); // Logs 10 because "total" is accessible globally
^ note that total
exists in the function too, but the above console.log gets the total
that’s in the global scope with the final value. If I feel the final total is not correct, I would put the console.log(total)
inside the function to see what’s going on in there before it’s sent out to the global scope.
Thanks for explaining. Much appreciated!