A variable’s scope is the context in which the variable exists. The scope specifies from where you can access a variable and whether you have access to the variable in that context.
Local Variables (Function-level scope)
다른 프로그래밍 언어와는 다르게, 자바스크립트는 block-level scope( {} if문이나 for, while loop문 같은..)를 가지고 있지 않다. 대신에 function-level scope로 정해지는데, 함수 안에 선언 된 변수는 지역 변수가 되고, 오직 그 함수 안에서 혹은 그 함수 안의 함수 내에서만 해당하는 지역 변수에 접근 할 수 있다.
Demonstration of Function-Level Scope
var name = "Richard";
function showName () {
var name = "Jack"; // local variable; showName 함수 내에서만 접근 가능하다.
console.log (name); // Jack
}
console.log (name); // Richard: the global variable
No Block-Level Scope
var name = "Richard";
// if 내에 있는 변수는 지역 context를 가지고 있지않고, 여전히 global 안에 있다. 자바스트립트 공부하면서 이상했던 것 중에 하나....
if (name) {
name = "Jack";
console.log (name); // Jack: still the global variable
}
// 여전히 글로벌 변수고, if 문에서 value가 바꼈을 뿐.
console.log (name); // Jack
- 로컬 변수를 선언하지 않으면 문제가 상당히 많이 발생하게 된다..
JSHint 같은 곳에서 syntax errors나 style guides를 확인해보는 것도 좋다!
로컬 변수를 사용하지 않았을 때 문제의 예시가 아래에 있다.
// 'var'를 써주지 않으면 자동으로 글로벌 변수가 된다.
var name = "Michael Jackson";
function showCelebrityName () {
console.log (name);
}
function showOrdinaryPersonName () {
name = "Johnny Evers";
// name은 함수 내에 있지만 글로벌 변수임
console.log (name);
}
showCelebrityName (); // Michael Jackson
showOrdinaryPersonName (); // Johnny Evers
showCelebrityName (); // Johnny Evers
function showOrdinaryPersonName () {
var name = "Johnny Evers"; // var를 써서 지역 변수가 됨.
console.log (name);
}
Global Variables
간단히 말해, 함수 밖에 있는 범위를 global scope라고 한다. 자바스트립트가 자주 쓰이는 브라우저에서는 global context나 global scope는 window object 또는 HTML 전체 문서가 된다.
어떤 변수든지 함수 밖에서 선언되거나 초기화되면 global 변수가 되고, 어플리케이션 내에 어디서든지 접근이 가능하게 된다.
주의 해야 할 몇 가지 예시들
function showAge () {
// var 없이 선언했기 때문에 자동으로 글로벌 변수가 됨.
age = 90;
console.log(age);//
}
showAge (); // 90
// age가 글로벌 변수기 때문에 밖에서도 로그가 찍힌다.
console.log(age); // 90
- 함수 내에서 변수를 선언했더라도 var를 붙이지 않으면, 자동으로 글로벌 변수가 된다. 왜 이렇게 만들었는지 모르겠음 –;;
for (var i = 1; i <= 10; i++) {
console.log (i); // outputs 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
};
function aNumber () {
console.log(i);
}
aNumber (); // 11
- 위 에서 이야기 했듯이, 자바스크립트에서 if, for, while 같은 { } 블락레벨 스코프가 존재하지 않는다. i 가 for 내에서 선언됐지만 i는 글로벌 변수임.
글로벌 스코프를 오염시키지 말자! 웬만하면 글로벌 변수를 사용하지 않는게 좋다
나쁜 예↓
// These two variables are in the global scope and they shouldn't be here
var firstName, lastName;
function fullName () {
console.log ("Full Name: " + firstName + " " + lastName );
}
좋은 예↓
// Declare the variables inside the function where they are local variables
function fullName () {
var firstName = "Michael", lastName = "Jackson";
console.log ("Full Name: " + firstName + " " + lastName );
}
Resource
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/