JS

[JS] javascript 변수선언(var, let, const)

져니져니95 2021. 3. 31. 10:06

2020.03.31(수)

블록체인 기반 핀테크 및 응용 SW 개발자 양성과정 열네번째날

 

 

1. var ( 옛날에 많이 쓰던 변수선언 방식, 최근에는 덜 쓰는편! )

 

 

 

 

2. let

let을 붙이면 사용현위치에 따라서 사용범위가 달라짐 최상위구간에 let을 사용하면 전체에서 사용, function안에서 쓰면 function안에서만 사용, fuction 안에 있는 let이 먼저 인식

 

    <script type="text/javascript">
    let index=10; //전역변수
    function hello(){

        console.log(index);
        index ++;
        
    }

    hello();
    hello();

    </script>

 

let으로 전역변수에는 index에 값 10을 주고, 지역변수에는 0을 주게 되면, 지역변수 let을 우선인식한다.

    <script type="text/javascript">
    let index=10; //전역변수
    function hello(){
        let index=0;
        console.log(index);
        index++;
        
    }

    hello();
    hello();
    hello();

    </script>

 

 

3. const

상수라는 의미로 변하지 않는 변수이다.

index ++같이 변수에 변화를 주는 것을 적용하게 되면 에러가 나옴

 

    <script type="text/javascript">
    const index=10; //전역변수
    function hello(){

        console.log(index);
        index ++;
        
    }

    hello();
    hello();

    </script>

만약 index ++; 를 빼주면 다음과 같은 결과값이 나오게 된다.