→ 나머지 : %
→ 거듭제곱 : **
→ 문자열에서 따옴표를 사용하는 방법
console.log(”I’m Iron man”);
console.log(”He said “I\’m Iron man\””);
console.log(’He said “I\’m Iron man\”‘);
console.log(”He said \“I\’m Iron man\””);
console.log(’He said \“I\’m Iron man\”’);
console.log(
He said \“I\’m Iron man\”);
g→ 불린 (Boolean)
같다 : ===
/ 같지 않다 : !==
AND : &&
/ OR : ||
/ NOT : !
typeof 값
→ 값의 자료형을 표시 (number string boolean function 등)
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Operator_precedence
우선순위 | 연산자 유형 | 기호 |
---|---|---|
21 | 그룹 | (...) |
... | ||
17 | 논리 NOT | ! ... |
17 | typeof | typeof ... |
16 | 거듭제곱 | ... ** ... |
15 | 곱셈 | ... * ... |
15 | 나눗셈 | ... / ... |
15 | 나머지 | ... % ... |
14 | 덧셈 | ... + ... |
14 | 뺄셈 | ... - ... |
... | ||
12 | 미만 | ... < ... |
12 | 이하 | ... <= ... |
12 | 초과 | ... > ... |
12 | 이상 | ... >= ... |
11 | 동등 | ... == ... |
11 | 부등 | ... != ... |
11 | 일치 | ... === ... |
11 | 불일치 | ... !== ... |
... | ||
6 | 논리 AND | ... && ... |
5 | 논리 OR | ... II ... |
... | ||
3 | 할당 | ... = ... |
String, Number, Boolean
console.log(Number(’10’) + Number(’5’));
→ 15
console.log(String(10) + String(5));
→ 105
true → 1 / false → 0, 빈 문자열, NaN (falsy 값)
산술 연산 (+, -, *, /, %, **)
console.log(4 + ‘2’);
→ 42관계 비교 연산 (<, <=, >, >=)
같음 비교 연산 (===, !==, ==, !=)
→ template : 일정한 틀, 형식
let year = 2024;
let month = 5;
let day = 30;
console.log(`생년월일은 ${year}년 ${month}월 ${day}일 입니다.`)
let myNumber = 3;
function getTwice(x) {
return x * 2;
}
console.log(`${myNumber}의 두 배는 ${getTwice(myNumber)}입니다.`);
// 숫자형과 문자열 재료
let material1 = 3;
let material2 = '3';
let material3 = 10;
let material4 = '4';
let material5 = 4;
// 연산 결과
let result1;
let result2;
// 연산을 통해 result1에 문자열 '34'를, result2에 숫자형 34를 할당
// 여기에 코드를 작성하세요
result1 = material2 + material4;
result2 = material1 * material3 + material5
// 테스트 코드
console.log(result1);
console.log(typeof result1);
console.log(result2);
console.log(typeof result2);
// 할당 연산자 (Assignment operators)
let x = 5;
x = x - 2;
console.log(x);
// 다음 세 줄은 같은 의미입니다
x = x + 1;
x += 1;
x++;
// 여기에 코드를 작성하세요
function logParticipant(name) {
console.log(`${name}(이)가 대화에 참여했습니다.`);
}
// 테스트 코드
logParticipant('동수');
logParticipant('윤하');
logParticipant('재준');
logParticipant('동훈');
logParticipant('영희');
logParticipant('신욱');
// 여기에 코드를 작성하세요
function expressMultiplication(num1, num2) {
let result = num1 * num2;
console.log(`${num1} * ${num2} = ${result}`);
}
// 테스트 코드
expressMultiplication(3, 4);
expressMultiplication(3, 2);
expressMultiplication(7, 5);
expressMultiplication(8, 9);
expressMultiplication(5, 5);
expressMultiplication(9, 9);
return
: 함수를 실행하고 어떤 값을 돌려주는 것
VS
console.log
: 콘솔의 어떤 값을 출력해주는 것
// 여기에 코드를 작성하세요
function calculateRectangleArea(num1, num2) {
return num1 * num2;
}
// 테스트 코드
let area1 = calculateRectangleArea(3, 4); // 가로 3, 세로 4인 직사각형의 넓이 계산
let area2 = calculateRectangleArea(5, 8); // 가로 5, 세로 8인 직사각형의 넓이 계산
let area3 = calculateRectangleArea(7, 2); // 가로 7, 세로 2인 직사각형의 넓이 계산
console.log(`Area1: ${area1}, Area2: ${area2}, Area3: ${area3}`);
function introduce(nationality = ‘한국’) {}
// 여기에 코드를 작성하세요
function orderSetMenu(sandwich, drink = '스프라이트') {
console.log(`주문하신 ${sandwich}, ${drink} 세트 메뉴 나왔습니다!`);
}
// 테스트 코드
orderSetMenu('코드웨잇 클럽');
orderSetMenu('터키베이컨 아보카도', '코카콜라');
orderSetMenu('코드웨잇 멜트');
orderSetMenu('이탈리안 비엠티', '닥터페퍼');
orderSetMenu('에그마요', '환타 오렌지');
const pi = 3.14;
→ 값 재할당 불가 이름 규칙 필요// 아래에 adultTag, teenagerTag, errorTag, transferTag라는 변수들을 작성해 주세요
let adultTag = '삑!';
let teenagerTag = '삑삑!';
let transferTag = '환승입니다.'
let errorTag = '삑삑삑!'
// 아래에 tagCase파라미터를 가지는 tagNotification() 함수를 작성해 주세요
function tagNotification(notice) {
console.log(`${notice}`)
}
// 테스트 코드
tagNotification(adultTag);
tagNotification(teenagerTag);
tagNotification(transferTag);
tagNotification(errorTag);
tagNotification(adultTag);
if (조건부분) {
동작부분
} else {
조건이 아닐 때 동작부분
}
// 파라미터 height을 활용하는 checkHeight 함수를 완성하세요
function checkHeight(height) {
// 여기에 코드를 작성하세요
if(height >= 140) {
console.log('탑승이 가능합니다.');
} else {
console.log('탑승이 불가능합니다.');
}
}
// 테스트 코드
checkHeight(140);
checkHeight(135);
checkHeight(170);
if (조건부분) {
동작부분
} else if (다른 조건부분) {
다른 조건일 때 동작부분
} else {
모든 조건이 아닐 때 동작부분
}
→ 간결하고 읽기 쉬운 코드 작성 가능 (not 중첩)
function printGrade(midtermScore, finalScore){
let totalScore = midtermScore + finalScore;
// 여기에 코드를 작성하세요
if (totalScore >= 90) {
console.log('A');
} else if (totalScore >= 80) {
console.log('B');
} else if (totalScore >= 70) {
console.log('C');
} else if (totalScore >= 60) {
console.log('D');
} else {
console.log('F');
}
}
// 테스트 코드
printGrade(25, 35);
printGrade(50, 45);
printGrade(29, 24);
printGrade(37, 42);
// 나의 나이와, 나의 성별을 저장하는 변수
let myAge = 26;
let myGender = 'male';
// 호칭을 담은 변수
let callOlderBrother = '형';
let callOlderSister = '누나';
let callFriend = '친구';
let callYoungerSister = '여동생';
let callYoungerBrother = '남동생';
// 상대방의 나이와 성별에 따른 호칭을 리턴하는 함수 whatShouldICall를 완성하세요
function whatShouldICallYou(yourAge, yourGender) {
// 여기에 코드를 작성하세요
if(yourAge == 26) {
return callFriend;
} else if(yourAge < 26) {
if(yourGender == 'male') {
return callYoungerBrother;
} else {
return callYoungerSister;
}
} else {
if(yourGender == 'male') {
return callOlderBrother;
} else {
return callOlderSister;
}
}
}
// 테스트 코드
let result1 = whatShouldICallYou(25, 'female');
let result2 = whatShouldICallYou(20, 'male');
let result3 = whatShouldICallYou(26, 'female');
let result4 = whatShouldICallYou(30, 'male');
let result5 = whatShouldICallYou(31, 'female');
console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);
console.log(result5);
switch (비교할 값) {
case 조건값 1 :
동작부분;
break;
case 조건값 2 :
동작부분;
break;
default :
동작부분;
}
→ break
: case별로 동작을 하고 끊어주는 역할
→ default
: 위의 모든 조건을 만족하지 않을 경우 실행
범위를 만족하는 조건식을 만들 때는 if
문을 활용하는 것이 효과적이고, 특정값을 만족하는 조건식을 만들 때는 switch
문이 효과적
if
문으로 대체할 때는 반드시 등호 세 개를 사용해 일치 비교를 해야 한다switch
문은 값들을 비교할 때 자료형을 엄격하게 구분한다// 각 등급별 가격
let VIPPrice = 15;
let RPrice = 13;
let SPrice = 10;
let APrice = 8;
// 각 등급에 맞는 가격을 출력하는 함수 checkPrice를 완성하세요
function checkPrice(grade) {
// 여기에 코드를 작성하세요
let price;
switch(grade) {
case 'VIP' :
price = VIPPrice;
console.log(`${grade}석은 ${price}만 원입니다.`)
break;
case 'R' :
price = RPrice;
console.log(`${grade}석은 ${price}만 원입니다.`)
break;
case 'S' :
price = SPrice;
console.log(`${grade}석은 ${price}만 원입니다.`)
break;
case 'A' :
price = APrice;
console.log(`${grade}석은 ${price}만 원입니다.`)
break;
default :
console.log('VIP, R, S, A 중에서 하나를 선택해 주세요.');
}
}
// 테스트 코드
checkPrice('R');
checkPrice('VIP');
checkPrice('S');
checkPrice('A');
checkPrice('B');
for(초기화 부분; 조건부분; 추가동작부분;) {
동작부분;
}
for(let i = 0; i < 10; i++) {
console.log(`${i} 코드잇 최고!`);
}
→ 초기화 부분 : 생성한 변수는 for문의 로컬 변수, 지역 변수
for (; i <= 10; i++)
→ 추가 동작 부분
i++;
과 같이 증가시키는 부분이 들어가도록 → 조건과 관련된 부분은 소괄호에 모아두는 것이 적합while (조건부분) {
동작부분
}
let i = 0;
while (i <= 10) {
console.log(`${i} 코드잇 최고!`);
i++;
}
→ 조건 부분이 충족하지 않을 때까지 동작 부분을 반복하여 실행
break
: 반복이 실행되는 중에 중단할 수 있는 역할continue
: 아래 동작이 실행되지 않고 다음 단계로 넘어가게 해주는 역할// 여기에 코드를 작성하세요
let result;
for(let i = 1; i < 10; i++) {
for(let j = 1; j < 10; j++) {
result = i * j;
console.log(`${i} * ${j} = ${result}`);
}
}
// 여기에 코드를 작성하세요
let num1 = 1;
let num2 = 1;
console.log(num1);
console.log(num2);
for (let i = 2; i < 50; i++) {
let result = num1 + num2;
console.log(result);
num1 = num2;
num2 = result;
}