DEV Community

Todd Chaffee
Todd Chaffee

Posted on • Updated on • Originally published at blog.toddbiz.com

JavaScript and Scope II - Functions

As you saw in the previous article about JavaScript scope, a function can create a new scope which determines the value to use when we have two different variables with the same name.

But is scope determined by where a function is declared, or where the function is run?

var i = 10;

function foo() {
  var i = 2;
}

function bar() {
  i = i + 1;
  console.log ('value of i when bar is declared outside foo: ', i);
}


foo();

bar();

Edit in JSFiddle

In the example above it should be obvious that i will have a value of 11 when console.log runs. But what happens if we run bar inside of foo? The answer might surprise you if you are new to JavaScript.

var i = 10;

function foo() {
  var i = 2;

  bar();

}

function bar() {
  i = i + 1;
  console.log ('value of i when bar is declared outside foo: ', i);
}


foo();

Edit in JSFiddle

The i variable again will have a value of 11 when console.log runs.

Because bar is declared in the global scope, it changes the value of the i variable that exists in the same global scope. Even when it runs inside of foo, it does not reference the i declared inside of the foo scope.

So what happens if we declare the bar function inside of the foo function?

var i = 10;

function foo() {
  var i = 2;

  function bar() {
    i = i + 1;
    console.log ('value of i when bar is declared inside foo: ', i);
  }

  bar();

}

foo();

Edit in JSFiddle

Hopefully you guessed that console.log will show i having a value of 3. The bar function is declared inside the scope of the foo function, so it will change and output the value of the i variable declared in the foo scope.

Many programming languages work like this, but not all of them so it's good to know the vocabulary for this. When scope is determined by where a function is declared (where it is written in the source code), we call it lexical scope. JavaScript uses lexical scope.

Learn more about scope in JavaScript and Scope III - Arrow Functions

Top comments (0)