> For the complete documentation index, see [llms.txt](https://k-developer.gitbook.io/dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://k-developer.gitbook.io/dev/javascript/undefined/undefined-5.md).

# 스코프

자바스크립트 스코프 알아보기

> 스코프란

스코프란 현재 접근할 수 있는 변수들의 범위를 말한다. 어떤 변수가 스코프안에 선언 되어있다면 이 변수는 스코프안에서만 접근하여 쓸수있다.

```javascript
var a = '글로벌';

function func() {
  var a = '함수안의변수';

  if (1) {
    var a = 'if문 변수'
    console.log(a); //1
  }

  console.log(a); //2
}
func();
console.log(a);//3
```

es6이전 방식인 var 키워드로 변수를 선언하고 스코프범위를 알아보자.

1. if문안이니 'if문 변수'가 출력된다.
2. func 함수안에서 사용하니 '함수안의변수'가 출력 될거같지만 'if문 변수'가 출력된다.
3. 글로벌에 선언된변수니 '글로벌'이 출력된다.

다른언어와 같이 블록스코프일거 같지만 var로 선언된 변수는 함수블록 기준으로 스코프가 설정된다.\
그래서 if문안의 a 할당문이 '함수안의변수' 값을 대체한다.

> var 키워드 선언 단점

1. 같은 이름변수로 재선언이 가능하다.
2. 스코프가 function 블록이다.

이제는 var 는 쓰여도 안되고 쓸 필요도 없다. es6이상 환경에서 변수선언 키워드인 let, const를 쓰면 위 단점모두 보완이 된다.이제는 실제로 쓸일이 없지만 만약에라도 es6이전 코드를 볼일이 생긴다면 알고있어야한다.

👉[const, let 알아보기](/dev/javascript/let-const/let-const.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://k-developer.gitbook.io/dev/javascript/undefined/undefined-5.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.
