DEV Community

Coder Pink
Coder Pink

Posted on

1 1 1 1 1

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more