bluehost-banner
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.

What is Scope in JavaScript?

Scope is defined as the accessibility of defined variables in JavaScript.

In JavaScript, there are three (3) types of scope namely:

1) Global Scope

2) Local Scope

3) Block Scope

1) Global Scope:

A Variable which is defined without any code block or function can have Global Scope

 The global scope variable can be accessed from anywhere within the program.

An example of a globally scoped variable is shown below:

let myVar= 'I am Global';
function callMe() {
    console.log(myVar);
}
// This function returns ‘I am Global’ as the response.
callMe();

2) Local Scope:

A Variable decaled within a function block can have local Scope.

They are only accessible within the function and cannot be used elsewhere within the program.

Below is an example of local scope:


function callMe() {
    let myVar= 'I am Local';
    console.log(myVar);
}
// This function returns ‘I am Local’ as the response.
callMe();

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