효땡 2024. 8. 5. 14:20

상수

- const

- 절대 변하지 않고 일정한 값

- 이름에 들어가는 모든 알파벳을 대문자로 작성

- 두 개이상의 단어가 들어갈 경우, 언더바( _ ) 사용 (ex. MY_NUMBER)

- 값을 재할당을 하게 되면 오류

const PI = 3.14; // 원주율
let radius = 0; // 반지름

// 원의 넓이를 계산하는 함수
function calculateArea() {
  return PI * radius * radius;
}

// 반지름에 따른 원의 넓이를 출력하는 함수
function printArea() {
  return `반지름이 ${radius}일 때, 원의 넓이는 ${calculateArea()}`;
}

radius = 4;
console.log(printArea()); // 반지름이 4일 때, 원의 넓이는 50.24

radius = 7;
console.log(printArea()); // 반지름이 7일 때, 원의 넓이는 153.86

radius = 8;
console.log(printArea()); // 반지름이 8일 때, 원의 넓이는 200.96

 

퀴즈

QUIZ 01

const x = 1500;

function myFunction() {
  x = 1500 * 1.5;
  console.log(x);
}

myFunction();
console.log(x);

 

정답

// 오류발생

- const (상수)의 경우 재할당이 불가능함

 

 

QUIZ 02

const X = 1500;
let x = 1000;

console.log(x);
console.log(X);

 

정답

1000
1500

 

실습

코드잇 마을에서는 대중교통을 이용할 때, 교통카드를 단말기에 태그하면 "삑!"하고 소리가 납니다. 그런데 항상 "삑!"소리만 나는 게 아니라 상황에 따라 다른데요. 청소년의 경우네는 "삑삑!", 승차권이 제대로 찍히지 않았을 경우에는 "삑삑삑!", 그리고 환승할 경우에는 "환승입니다."라는 소리가 납니다.

 

각 상황의 소리를 담을 adultTag, teenagerTag, errorTag, transferTag 변수를 만드세요. 이 변수들을 파라미터(tagCase)로 전달하면 각 상황에 맞는 소리를 콘솔에 출력하는 tagNotification()함수를 만들어보세요.

 

// adultTag, teenagerTag, errorTag, transferTag라는 변수들을 작성
const adultTag = '삑!';
const teenagerTag = '삑삑!';
const errorTag = '삑삑삑!';
const transferTag = '환승입니다.';

// tagCase파라미터를 가지는 tagNotification() 함수를 작성
function tagNotification(tagCase) {
  console.log(tagCase);
}

// 테스트 코드
tagNotification(adultTag);
tagNotification(teenagerTag);
tagNotification(transferTag);
tagNotification(errorTag);
tagNotification(adultTag);

 

실습 결과

삑!
삑삑!
환승입니다.
삑삑삑!
삑!