when executing this javascript code
let bar = 'bar';
function foo() {
return bar;
}
console.log(foo());
bar = 'baz';
in the browser it logs baz
and in node.js it logs bar
, why does that happen ?
and wouldn’t bar
be more intuitive at this point ?
2
Answers
It looks to me that you run this code in the browser’s dev tools. In that case, you should (and I’m pretty confident you actually do) first see
bar
as the output of theconsole.log(foo());
call. Then, afterbar
, you get'baz'
as an additional line of output.This additional
'baz'
comes from the last line of your code. Thebar = 'baz';
assignment does two things:'baz'
to the variable'baz'
in this case.That’s why you see this in the output.
If you paste the code in an actual script you won’t see the additional output. See here:
It outputs only
bar
.Really an interesting question. But I think you may not have figured out who is the output in the console. When we execute code in the console, the browser always displays the return value of the last code. As this,
bar = 'baz'
return ‘baz'(test it byconsole.log(bar = 'baz')
) and it shows, the real output ofconsole.log(foo());
comes before this.If you are still confused about this, execute it: