0

I wonder why the function can see the variables "a" and "b" even though they are declared and defined outside of the function scope?

function whichOneGreater() {
  a > b ? console.log("a: ", a) : console.log("b: ", b);
}

var a = 3/4;
var b = 4/9;

whichOneGreater()

if I change the variable name from a to c

function whichOneGreater() {
  a > b ? console.log("a: ", a) : console.log("b: ", b);
}

var c = 3/4;
var b = 4/9;

whichOneGreater()

then the error happens

script.js:2 Uncaught ReferenceError: a is not defined
    at whichOneGreater (script.js:2)
    at script.js:8

Edit: I found an article that answers my question well here

John
  • 1
  • 2
  • 1
    Why wouldn't it be able to see those variables? – VLAZ Mar 24 '20 at 20:32
  • 1
    @VLAZ, I thought for the function encapsulation, a function only sees whatever is defined inside its body, not the outside, right? – John Mar 24 '20 at 20:35
  • it is because of javascript variable hoisting , wherever you define the variable in the file at runtime it always hoist the variable up and declare that – Suraj Mar 24 '20 at 20:40
  • @Suraj hoisting is completely unrelated in this case. – VLAZ Mar 24 '20 at 20:51
  • @John a function has access to everything in its inner scope *and* every outer scope. Since `a` and `b` are defined in the same scope as `whichOneGreater()`, then the function can see them. If there was another function defined inside `whichOneGreater()`, then it would also have access to `a` and `b`. – VLAZ Mar 24 '20 at 20:52
  • Thank you. I understand it now. – John Mar 25 '20 at 12:38

0 Answers0