node.js var, let, const의 차이

limchard·2023년 12월 6일
0

node.js

목록 보기
2/7

var : 함수형 변수

재선언가능, 업데이트 가능.

var hello="안녕";
var hello="헬로우";
var cnt=5;

if(cnt<6){
    var hello1="say hello~~";
    console.log(hello1);
}
// if(cnt>6){
//     var hello1="say hello~~";
//     console.log(hello1);
// }

console.log(hello1);
console.log(hello);

콘솔:

say hello~~
say hello~~
헬로우

let : 재선언 불가능, 업데이트 가능

블록 {}에 선언된 변수는 블록내에서만 사용 가능하다.

let hi="hi";
hi="하이라고 할께";

let times=5;
if(times>3){
    let hi1="say Hi~~~";
    console.log(hi1);
}
// console.log(hi1);
console.log(hi);

콘솔:

say Hi~~~
하이라고 할께

const : 재선언 불가능, 업데이트 불가능

const hi3="안녕";
// hi3="하이";

const hi4={
    message:"4th say Hi~~~",
    times:4
}
console.log(hi4);

콘솔:

{ message: '4th say Hi~~~', times: 4 }
hi4.message="이렇게는 될까?"; // 중간에 값 수정 가능
console.log(hi4);

콘솔:

{ message: '이렇게는 될까?', times: 4 }
hi4.times=44; // 중간에 값 수정 가능
console.log(hi4);

콘솔:

{ message: '이렇게는 될까?', times: 44 }

함수에서도 당연히 동일하다.

var a=1;
let b=2;

function myFunction(){
    var a=3;
    let b=4;

    if(true){
        var a=5;
        let b=6;

        console.log(a); // 5
        console.log(b); // 6
    }
    console.log(a); // 5
    console.log(b); // 4

}
myFunction();

console.log(a); // 1
console.log(b); // 2
5
6
5
4
1
2
profile
java를 잡아...... 하... 이게 맞나...

0개의 댓글