skip to Main Content

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


  1. 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 the console.log(foo()); call. Then, after bar, you get 'baz' as an additional line of output.

    This additional 'baz' comes from the last line of your code. The bar = 'baz'; assignment does two things:

    1. Assigns 'baz' to the variable
    2. Returns the right-hand side value of the assignment, which is '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:

    let bar = 'bar';
    function foo() {
      return bar;
    }
    console.log(foo());
    bar = 'baz';

    It outputs only bar.

    Login or Signup to reply.
  2. 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 by console.log(bar = 'baz')) and it shows, the real output of console.log(foo()); comes before this.enter image description here

    If you are still confused about this, execute it:

    (() => {
      let bar = 'bar';
      function foo() {
        return bar;
      }
      console.log(foo());
      bar = 'baz';
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search