What is Scope in JavaScript?

What is Scope in JavaScript?

In this post, I you will learn step by step how the scope works in JavaScript.

Block scope:

  A block of code defines scope for variables which can declared using let and const.

if (true) {
  //block scope
  const greeting= 'Hello';
  console.log(greeting); // 'Hello'
}
console.log(greeting); // throws ReferenceError

In Above example console.log inside the if block will correctly logs the output but the second console.logs which is outside the if block will give reference error because its outside the scope means it is not exist.

var is not block scoped:

As you see in the above example, the code block creates a scope for variables which declared using const and let. but, that’s not the case of variables declared using var

if (true) {
  //block scope
  var number = 0;
  console.log(number ); // 0
}
console.log(number ); // 0

Here number variable is accessbile outside the if block scope.

So, rememebr this,

  A code block does not create a scope for var variables, but a function body does.

Function scope:

  A function in JavaScript defines a scope for variables which declared using var, let and const.  

function show() {
  //function scope
  var greeting = 'Hello!';
  console.log(greeting ); // 'Hello!'
}

run();// 'Hello;
console.log(greeting ); // throws ReferenceError

In Above example show function creates a scope. The variable greeting is accessible inside of the function scope, but inaccessible outside.

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment