React Native
var let const 의 차이(react native)
SallyJ
2022. 9. 29. 11:07
var, let, const 전부다 int 값도 String 값도 다 받을 수 있다.
하지만 var 의 경우 똑같은 변수를 사용해도 에러가 뜨지 않는다.
몇백줄, 몇천줄의 코드를 작성하다보면 내가 어떤 변수를 사용했는지 기억을 못해서 같은 변수를 사용할 수도 있는데,
그때는 내가 원하지 않는 곳에 새로운 값이 입혀질 수도 있다
그래서 난 let을 사용하는 것을 권장한다.
var hello = 'world';
var hello = 'react-native'
console.log(hello); // 에러없이 결과값이 react-native 가 나온다
하지만 var 대신에 let을 쓰면 에러가 뜬다.
요 경우에는 글로벌변수와 로컬 변수이기 때문에 당연하게도 내가 원하는 값이 그대로 나온다
var hello = 'world'; // global 변수
function test() {
var hello = 'react-native'; // local 변수
console.log(hello);
}
test(); // react-native
console.log(hello); // world
하지만 function 이 아닌 if 문이라면?
var hello = 'world';
if(true) {
var hello = 'react-native';
console.log(hello); // react-native
}
console.log(hello); // react-native
react-native 가 두번 나온다. 이것도 당연한 결과다.
이번엔 var를 let으로 바꿔보자.
let hello = 'world';
if(true) {
let hello = 'react-native';
console.log(hello); // react-native
}
console.log(hello); // world
react-native 가 한번, world 가 한번 나온다.
let은 변수를 선언한 블럭에서 유효하다.
그래서 var 보다는 let을 사용하는것을 권장한다.(개인적인 의견)
const의 경우 java의 final처럼 한번 정의가 된 값은 변하지 않는다.
하지만 다른점이 있다면, 객체나 배열의 요소 수정은 가능하다.
// object
const fruit = {};
fruit.apple = 'red';
fruit.banana = 'yellow';
console.log(fruit) // {apple: 'red', banana: 'yellow'}
// array
const arr = [ 0, 1, 2, 3, 4, 5, 6 ]
arr[0] = 100;
arr[3] = 33;
console.log(arr) // [100, 1, 2, 33, 4, 5, 6]