DEV Community

Todd Chaffee
Todd Chaffee

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

1 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay