변수는 어떠한 환경 내에서만 사용 가능하며, 프로그래밍 언어는 각각의 변수 접근규칙을 갖고 있다.
변수와 그 값이, 어디서부터 어디까지 유효한지를 판단하는 범위
JavaScript는 기본적으로, 함수가 선언되는(lexical) 동시에 자신만의 Scope를 가진다.
Local Scope 안쪽에서 선언된 변수는 밖에서 사용할 수 없다
let greeting = 'Hello'; function greetSomeone() { let firstName = 'Josh'; return greeting + ' ' + firstName; } greetSomeone(); // "Hello Josh" firstName // Uncaught ReferenceError: firstName is not defined
let name = 'Heaeun';
function showName() {
let name = 'Daeun'; // 지역변수
/*
* 1. let 키워드를 이용해 새로 선언하였으므로,
전역에 선언한 name과는 다른 변수이다
* 2. showName 함수 안에서만 접근 가능
*/
console.log(name);
}
console.log(name); // Heaeun
showName(); // Daeun
console.log(name); // Heaeun
let name = 'Heaeun';
function showName() {
name = 'Daeun'; // 전역변수
/*
* 1. 선언(let)이 없기 때문에,
바깥 scope에 있는 name이라는 변수를 가져온다
*/
console.log(name);
}
console.log(name); // Heaeun
showName(); // Daeun
console.log(name); // Daeun
👉 Block : 중괄호로 시작하고 끝나는 범위
if(true) {
console.log('i an in the block');
}
for (let i = 0; i < 10; i++) {
console.log(i);
}
{
console.log('it works');
}
👉 var 키워드 VS let 키워드