-
2. Variable Declaration(변수 선언)FrontEnd/Javascript 2022. 2. 7. 16:11728x90
변수란..?
변할 수 있는, 가변적이라는 의미를 내포하고 있으면서 프로그래밍에서는 저장이라는 단어를 사용하고 있다.
쉽게 말하면
"하나의 값을 저장할 수 있는 저장공간"
이라고 할 수 있다.
JavaScript의 데이터 타입의 종류
데이터 타입(Data Type)은 프로그래밍 언어에서 사용할 수 있는 데이터의 종류를 말한다.
자바스크립트에서 제공하는 7개의 데이터 타입은 크게 원시 타입(primitive data type), 객체 타입(object/reference type)
로 구분할 수 있다.
- 원시 타입 (primitive data type) - 변경 불가능한 값
- boolean
- null
- undefined
- number
- string
- symbol (ES6에서 추가)
- 객체 타입 (object/reference type) - 이름과 값을 가지는 데이터
- object
변수 선언 방식
var 키워드로 선언한 변수는 중복 선언이 가능하다.
// DateType name = value; var value = "안녕하세요!"; //변수선언과 동시에 초기화하는 습관을 들이자!! console.log(value); var value = "조심히가세요!"; console.log(value);
그래서 ES6 이후, 이를 보완해서 나온 변수 선언 방식이 let과 const이다.
이 둘의 차이점은 immutable(변하지 않음)이다.
let은 변수에 재할당이 가능하다. 하지만,
let brand = 'Samsung' console.log(brand) //Samsung let brand = 'Apple' console.log(brand) //Uncaught SyntaxError: Identifier 'brand' has already been declared brand = 'LG' console.log(brand) //LG
const는 변수 재선 언, 변수 재할당 모두 불가능하다.
const brand = 'Samsung' console.log(brand) // Samsung const name = 'Apple' console.log(brand) // Uncaught SyntaxError: Identifier 'brand' has already been declared brand = 'LG' console.log(name) //Uncaught TypeError: Assignment to constant variable.
정리..
어떤 변수 선언 방식을 사용하는 게 좋을까?
재할당이 필요한 경우에만 let을 사용하고 기본적으로 const를 사용하는 것이 좋다.
객체를 재할당하는 경우는 많지않기 때문에 const를 사용해 의도치 않은 재할당을 방지하는 게 낫다.
'FrontEnd > Javascript' 카테고리의 다른 글
React에서 많이 사용하는 Javascript 문법 (0) 2022.05.10 5. 반복문(loop) (0) 2022.02.18 4. 제어문(Condition) (0) 2022.02.17 3. 연산자(Operators) (0) 2022.02.17 1. Javascript! 안녕! (0) 2022.02.07 - 원시 타입 (primitive data type) - 변경 불가능한 값