# Scope

#### Function Scope:

* Every Execution context has a link with the outer environment or link with its parent environment.

```javascript
var name = "Vijay";
function sayName() {
    console.log(name); // Vijay
    var nickName = "Deepak";
    console.log(nickName); // Deepak
    return function subName() {
        console.log(name); // Vijay
        console.log(nickName); // Deepak
        var nickName2 = "Vishnu";
        console.log(nickName2); // Vishnu
    }
    console.log(nickName2); // Reference Error: nickName2 id not defined
}

var myNameFn = sayName();
myNameFn();

```

we can access the parent variables from any of its child, but not from parent to child.

![Global/Function Lexical Environment of the Example above](/files/-LlLPFcn5If2bNvOpW9Q)

**Note:** As mentioned in the optimized code topic not to use eval() and with in JavaScript,  it may confuse the JavaScript engine regarding the scope while optimizing the code, some times it may de-optimize the code.

#### Block Scope:

&#x20;   A variable created inside a curly braces "{ }", cannot be accessible outside.

* Block scope is introduced in JavaScript as ES6.
* variables should be declared with "let" or "const" key word.

#### Function VS Block Scope:

```javascript
// Function Scope
function alpha() {
    var message = "Hello";
}
console.log(message); // Reference Error: message is not defined
if (5>1) {
    var message = "Hello";
}
console.log(message); // Hello

// Block Scope
if (5>1) {
    let message = "Hello";
    const name = "John";
}
console.log(message); // Reference Error: message is not defined
console.log(name); // Reference Error: name is not defined
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascript-1.gitbook.io/javascript/scope.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
