javascript
let, const 선언
토마토오이
2021. 4. 11. 21:01
javascript에서 변수 선언 시, var / let / const 방식이 있다.
1. var
: 변수 선언 후 같은 변수를 여러번 선언해서 값을 변경할 수 있다.
2. let:
선언 한 경우 선언한 변수 명을 여러번 선언할 수 없으며 값을 변경 할 수 있다.
ex )
let v = “test”;
> 실행결과 : “test”
let v = “abc”;
> 실행결과 : Uncaught SyntaxError: Identifier 'a' has already been declared
v = “test123”;
v = “test123”;
> 실행결과 : “test123"
let은 재선언은 안되지만, 선언 후 값은 변경 할 수 있다.
3. const
: 선언한 변수명을 재선언 할 수 없으며 값을 변경 할 수 없다. 선언과 동시에 초기화를 해야 에러가 나지 않는다.
ex )
const c = “ha”;
> 실행결과 : “ha”
const c = “wow”;
> 실행결과 : Uncaught SyntaxError: Identifier 'c' has already been declared
c = “wow!!!”;
> 실행결과 : Uncaught TypeError: Assignment to constant variable.
const는 재선언도 안되며, 선언 후 값 변경도 안된다.
Const 를 object형식으로 선언하면 value값을 변경 할 수 있다.
ex)
const objTest2 = {test1 : "test1", test2 : "test2”};
objTest2.test1 = "te”;
console.log(objTest2.test1);
console.log(objTest2);
> 실행결과 :
“te"
{test1: "te", test2: "test2”}
위와 같이 변경 할 수 있다.