Skip to content

Try our new Crash Courses!

Become a member using the button below to hide this banner and gain access to our new Crash Courses.

Function scope – JavaScript

Length: 10 minutes

Summary

In JavaScript, if you declare a variable using let or const inside a function, you can’t use it outside of that function.

function scopeTest() {
  let a = 1;
  const b = 'hello';
}

// This will cause an error
console.log(a);
console.log(b);

Details

If you declare a variable using let or const inside of a function, you can use it normally inside of that function.

function scopeTest() {
  let a = 1;
  const b = 'hello';
  // These statements will work
  console.log(a);
  console.log(b);
}

However, if you try to access a variable or constant declared inside a function outside of it or from a different function, you will get an error in the console.

function scopeTest() {
  let a = 1;
  const b = 'hello';
}

  // These statements will NOT work
  console.log(a);
  console.log(b);

Demo

Exercises

Try the following statements in the console:

function scopeTest() {
  let a = 1;
  const b = 'hello';
}

a
b

You should see errors appear in the console.

References

Functions on MDN

Back to: JavaScript Reference > JS Functions