0

I'm reading some books, learning javascript, and i see that javascript uses lexical scope.

Lexical scoping means whatever variables are in scope where you define a function from (as opposed to when you call it) are in scope in the function

I tried some basic example:

function f() {
  console.log(x);
}
const x = 10;
f(); // 10

Then how does this work, and why does it log value 10? Variable x doesn't exist when I define the function. I'm javascript noob, so maybe I'm missing something here. Thanks in advance.

ivke11080
  • 9
  • 1
  • Check [this video](https://www.youtube.com/watch?v=ByG-RU5fCcQ&t=52s) on 6:50. It describes lexical scope nicely. I found it helpful. – Mamun Morshed Jan 11 '17 at 09:47

1 Answers1

0

This is due to a concept named Hoisting. Essentially, any declaration is moved to the top of the scope, and hence is always accessible anywhere in the scope.

During the time your function id being defined, a lexical scope captures the reference to x.

Post which x is assigned 10.

Read more about hoisting in JS here. (JavaScriptisSexy.com) More specifically about Hoisting and const here.

Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
  • Hoisting is irrelevant here (and the assignment is not hoisted above the function declaration anyway). Uses of assignment operators are never hoisted. The `const` keyword (unlike `var`) isn't hoisted either. – Quentin Jan 11 '17 at 09:42
  • The reference is though. – Sunny R Gupta Jan 11 '17 at 09:42
  • Re edit: No. `const` statements are not hoisted. [This](http://jsbin.com/cogubon/1/edit?js,console) throws a reference error because `const` is not hoisted. [This](http://jsbin.com/cogubon/2/edit?js,console) throws a Syntax Error because you can't have a constant without assigning a value to it (or assign a value to it later) – Quentin Jan 11 '17 at 09:44
  • https://rainsoft.io/javascript-hoisting-in-details/#hoistingandconst Const is hoisted, (but still in the temporal dead zone till assigned a value). But of course the reference still exist. – Sunny R Gupta Jan 11 '17 at 09:47