DEV Community

Coder Pink
Coder Pink

Posted on

Scope in JavaScript (Block Scope and Function Scope)

Image description

Scope... Scope determines the accessibility of variables.

In JavaScript we'll create variable with var, let, and const keyword. they will create scope, that means we can only access the variable within the scope.

Block Scope: let and const create Block Scope. When we create a variable with let and const, they will create block scope means they can only access the block they are declared or created in.

So let's take a look at the example below:

if (true) {
    let one = "one";
    console.log(one); // "one"
}

console.log(one); // Uncaught Reference Error: one is not defined

Enter fullscreen mode Exit fullscreen mode

From the above example... we can see that we get an error when we console.log to the variable one outside the if statement.
Because variable one is declared within the if statement... its scope is only limited to the if statement. and we cannot access the let one outside the if statement.

Function Scope: Variable that are declared inside of a function will create a function scope. this means you can only access the value within the function there or the parent function.

Let's take a look at the example below:

function fun(b) {
  var a = 12;
  return a + b;
}

fun(5);// 17  fun is being called
console.log(a); // Uncaught Reference Error: a is not defined
Enter fullscreen mode Exit fullscreen mode

From the above example... we can see that we get an error when we were trying to access the variable a outside the function that says a is not defined as we read above.
So remember when you put or declared a variable inside the function, then it is only local to that function.

Top comments (0)