2019년 12월 20일 금요일

Javascript 변수 선언 키워드 Let 과 Const




* let and const

let : 블럭 사이에서만 활성 되는 변수 선언 키워드. 글로벌하게 사용할 수 있는 var 키워드와는 반대이다. 스코프를 벗어나면 해당 변수를 사용할 수 없다.
또한 let 으로 선언된 변수는 동일한 이름으로 다시 let으로 선언할 수 없다. (var는 가능함)

const : 상수. 값을 레퍼런스로써 읽기만을 하기 위한 변수 선언 키워드이다.
한번 할당하면 값을 변경할 수 없다. const로 선언된 변수는 반드시초기화를 해주어야 한다.


* 문제
PI 를 상수로 선언하고 r를 입력받아, 원의 넓이와 원둘레를 구하라.


function main() {
    // Write your code here. Read input using 'readLine()' and print output using 'console.log()'.
    const PI = Math.PI;
    let r = readLine();
    // Print the area of the circle:
    console.log(r * r * PI);
    // Print the perimeter of the circle:
    console.log(2 * r * PI);
    try {    
        // Attempt to redefine the value of constant variable PI
        PI = 0;
        // Attempt to print the value of PI
        console.log(PI);
    } catch(error) {
        console.error("You correctly declared 'PI' as a constant.");
    }
}

댓글 없음:

댓글 쓰기