[JavaScript] 변수(Variable), 스코프(Scope), 식별자(Identifier)
📌 변수(Variable), 스코프(Scope), 식별자(Identifier)
📍변수 (Variable)
- 변수는 데이터를 저장하는 가상의 공간으로 값을 저장하고 필요 시 사용할 수 있습니다.
- var, let, const 를 사용하여 선언
📗 var - 함수 스코프(function scope)를 가짐, 재선언 가능
- 재선언 및 재할당 가능
- 초기화하지 않으면 undefined 값을 가짐
- 숫자가 아닌 값을 연산하면 NaN(Not a Number) 발생 가능
- ES6 이전에 주로 사용
var name = "tistory";
console.log(name); // tistory
var name = "naver"; // ✅ 같은 변수 재선언 가능(변경)
console.log(name); // naver
📗 let - 블록 스코프(block scope)를 가짐, 재선언 불가능
- 같은 이름으로 재선언 불가능
- 변수의 값을 바꾸는 것은 가능
- 초기화하지 않으면 undefined 값을 가짐
- ES6(ECMAScript 2015) 문법에서 추가
let age = 99;
console.log(age); // 99
// let age = 1; ❌ 같은 변수명으로 다시 선언 불가
age = 66; // ✅ 값 변경 가능
console.log(age); // 66
📗 const - 블록 스코프(block scope)를 가짐, 재선언 및 값 변경 불가능
선언과 동시에 값을 반드시 할당해야 함
- 선언과 동시에 값을 반드시 할당해야 함
- 선언한 변수의 값을 변경할 수 없음
- 객체와 배열은 참조를 변경할 수 없지만 내부 값 수정은 가능
- ES6(ECMAScript 2015) 문법에서 추가
const year = 2222;
const test; // ❌ 선언 후 나중에 값 할당 불가능
const year = 2025; // ❌ 동일한 변수명 재선언 불가능
year = "2000"; // ❌ 재할당 불가능
const tistoryInfo = {
name: "th",
age: 99
};
person = { name: "blog", age: 55 }; // ❌ 객체 자체를 변경하는 것은 불가능
// ✅ 객체의 속성 수정 (가능)
tistoryInfo.age = 30;
console.log(person.age); // 30
const numbers = [1, 2, 3, 4];
numbers[0] = 100; // 요소 변경 가능
numbers.push(5); // 요소 추가 가능
numbers.pop(); // 요소 제거 가능
numbers = [4, 5, 6]; ❌ 배열 자체를 변경하는 것은 불가능
📍스코프 (Scope)
- 변수, 함수, 객체 등이 유효한 범위
📗 전역 스코프(Global Scope)
- 전역 영역에 선언된 변수는 어디서든 접근 가능 (가급적 피하는 것이 좋다 - 의도치 않은 변경 방)
var globalVar = "전역 변수";
function test() {
console.log(globalVar); // 전역 변수
}
test();
console.log(globalVar); // 전역 변수
📗 함수 스코프(Function Scope)
- 함수 내부에서만 접근 가능한 스코프
function example() {
var exampleValue = "test";
console.log(exampleValue); // test
}
example();
console.log(exampleValue); // ❌ 오류
📗 블록 스코프(Block Scope)
- {} 블록 내부에서만 접근 가능한 스코프
- let, const 사용 시 블록 스코프
if (true) {
let blockValue = "Block Scope";
console.log(blockValue); // Block Scope
}
console.log(blockValue); // ❌ 오류!
if (true) {
var blockTest = "Block Test";
}
console.log(blockVar); // ⚠️ Block Test 접근 가능
// ✅ let, const 사용
📗 렉시컬 스코프 (Lexical Scope)
- 선언된 위치(계층)에 따라 접근 가능한 스코프
- 함수 호출 위치가 아닌 "함수가 선언된 위치"에 따라 상위 스코프를 찾음
function wrap() {
let wrapValue = "wrap text";
function inner() {
console.log(wrapValue); // ☝️ ✅ wrap text
}
return inner;
}
const innerFunc = wrap();
innerFunc(); // wrap 변수
📗 모듈 스코프 (Module Scope)
- 모듈(import, export) 내부에서만 접근 가능한 스코프
- 각 모듈은 독립적인 스코프
- 다른 모듈에서 직접 접근할 수 없 접근하기 위해 export, import해야만 사용할 수 있다
// moduleA.js
export const moduleScopeA = "moduleScopeA";
// moduleB.js
import { moduleScopeA } from './moduleA.js';
console.log(moduleScopeA); // moduleScopeAd
// moduleA.js
const moduleScopeA = "moduleScopeA"; // export ❌
// moduleB.js
console.log(moduleScopeA); // ❌
📍 식별자 (Identifier)
변수, 함수, 프로퍼티, 클래스 등 식별하기 위해 사용하는 이름
📗 식별자 규칙
1. 대소문자를 구분
test와 Test는 다른 변수
2. 특수문자는 달러기호($), 밑줄(_)로 시작 가능
_test, $test
3. 첫 글자로 숫자를 사용할 수 없다 첫 문자 이후 사용 가능
1Test, 33test : ❌
Test1, test33 : ✅
4. 공백(띄어쓰기) 사용 불가
test box, user info - ❌
5. 예약어 사용 불가
// 👇 예약어
break case catch class const continue
debugger default delete do else export
extends finally for function if import
in instanceof new return super switch
this throw try typeof var void
while with yield enum implements interface
package private protected public static await
📗 식별자 허용 문자
- 문자(a-z, A-Z)
- 숫자(0-9, 첫 글자로는 사용 불가)
- 밑줄(_)
- 달러 기호($)
- 유니코드 문자(예: 한글, 일본어, 중국어 등)
※ 그 외의 모든 특수 문자(%, @, #, !, & 등)는 JavaScript 식별자에 사용 불가
📗 유효한 식별자
// 👇 유효한 식별자
// 변수
let tistoryName = "TH";
const tistoryID ="Tistory"
const $el = document.getElementById("tistory");
let _tistoryValue = 42;
let tistory99 = 99;
// 상수
const DEFAULT_NUMBER = 3;
// 함수
function userInfo() { ... }
const userLists = () => { ... }
// 클래스
class TistoryBlog { ... }
✍️ 기록
감사합니다. 😁