Hello there! Today, we'll explore some advanced concepts related to logic and conditionals in programming. Don't worry if you're not yet confident in these areas - I'll guide you through each step and introduce some Korean technical vocabulary to help you better understand the concepts.
As we dive into these topics, we'll encounter a charming mascot named 머쓱이, who represents Programmers.co.kr. Let's get started!
Operators | 연산자
We already are familiar with arithmetic operators (addition, subtraction, division, multiplication, remainder) but now it's time to get to know comparison operators.
Comparison operators are used to compare two values and return a boolean value (either true
(긍정, 참) or false
(부정, 거짓)) based on the result of the comparison (비교). If you are not sure how to use them, I recommend going through javascript.info's JavaScript Fundamentals: Comparisons.
if... else
statement | if... else
조건문
We use if... else
to make decisions in code. It works by checking a condition (조건) (like whether a number is greater than 1), and then performing different actions based on whether the condition is true
(긍정, 참) or false
(부정, 거짓).
let number = 1
if(number === 1) {
console.log('Oho! The number is 1!') // This is the output.
} else {
console.log('The number is not 1.')
}
If we were to change number
to another number, for example, 3:
let number = 3
if(number === 1) {
console.log('Oho! The number is 1!')
} else {
console.log('The number is not 1.') // This is the output.
}
Then the console would log out the 'Oh! The number is not 1.' from the else
statement.
We can also add multiple conditions (조건) by adding else if (condition)
between if
and else
elements:
let number = 3
if(number === 1) {
console.log('Oho! Number is 1!')
} else if (number > 1) {
console.log('Not 1 but bigger than 1.') // This is the output.
} else {
console.log('Hmm... Number is not 1.')
}
And it is also worth mentioning that else
is optional and we can have standalone if
statements (if
조건문) or if... if else
statements (if... if else
조건문) too:
let number = 1
if(number === 1) {
console.log('Oho! Number is 1!') // This is the output.
}
if(number > 0) {
console.log('Number is bigger than 0!') // This is also the output.
}
Here, both statements evaluate true
and get logged out because they are not combined into one statement.
Ternary operator | 삼항 연산자
Now that you are a bit more comfortable with conditional statements, let's take a look at something even cooler - the ternary operator.
The ternary operator, also known as the conditional operator, is a shorthand way of writing a if...else
statement. It has the following syntax:
condition ? expression1 : expression2
The condition
is evaluated first. If it is true
, expression1
is executed. If it is false
, expression2
is executed. Here's a real-life example:
let age = 22
let message = age >= 18 ? "You are an adult" : "You are not an adult";
console.log(message) // Output: "You are an adult"
If age
is greater than or equal to 18, the value of the message
variable will be "You are an adult", and if it is less than 18, the value of the message
will be "You are not an adult". The value of the message
variable is determined by the result of the ternary operator.
Ternary operators can also be chained together. This technique is used to simplify nested if...else
statements or switch cases. It allows you to write a single line of code that performs multiple conditional checks and returns different values based on those conditions.
condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : defaultValue
const temperature = 20;
const isRaining = false;
const message = temperature > 30 ? "It's hot outside" :
isRaining ? "It's raining outside" :
"It's a nice day outside";
console.log(message); // Output: It's a nice day outside
The ternary operator can make code more concise and readable in some cases, but it can also make code harder to read if it is overused. I'll show you an example later when solving one of the challenges. When it comes to the ternary operator, it is best to use it only when it improves the clarity of the code.
Vocabulary
Nouns:
변수 - variable
문자열 - string
숫자 - number
불린 - boolean
배수 - multiple (a number that can be divided by another number without a remainder)
짝수 - even (number)
홀수 - odd (number)
if... else
조건문 - if... else
conditional statement
삼항 연산자 - ternary operator
조건 연산자 - conditional operator
긍정, 참 - true
부정, 거짓 - false
거짓같은 값 - falsy
참 같은 값 - truthy
논리 연산자 - logical operator (&&, ||, !
)
논리곱 연산자 - AND operator (&&
)
논리합 연산자 - OR operator (||
)
논리부정 연산자 - NOT operator (!
)
관계연 산자 - relational operator (==, ===, !=, !==, <, >, <=, >=
)
동등 연산자 - equality operator (==
)
일치 연산자 - strict equality operator (===
)
부등 연산자 - inequality operator (!=
)
불일치 연산자 - strict inequality operator (!==
)
작음 - less than (<
)
큼 - greater than (>
)
크거나 같음 - greater or equal to (>=
)
작거나 같음 - less or equal to (<=
)
for
(반복)문 - for
loop
코드 블록 - code block
형 변환 - type conversion
예각 - acute angle
직각 - right angle
둔각 - obtuse angle
평각 - straight angle
Verbs:
조건을 평가하다 - to evaluate the condition
만족하다 - to be satisfied (a condition)
실행하다 - to run (a statement)
반환하다 - to return (a value)
비교하다 - to compare
반복하다 - to repeat
Phrases:
condition1
을 만족하면 statement1
을 실행하다.
if condition1
is satisfied run statement1.
Challenges
n의 배수
Description
수
num
과n
이 매개 변수로 주어질 때,num
이n
의 배수이면 1을 returnn
의 배수가 아니라면 0을 return하도록 solution 함수를 완성해주세요.제한사항
2 ≤
num
≤ 1002 ≤
n
≤ 9입출력 예
num n result 98 2 1 34 3 0 입출력 예 설명
입출력 예 #1
- 98은 2의 배수이므로 1을 return합니다.
입출력 예 #2
- 32는 3의 배수가 아니므로 0을 return합니다.
Description:
n의 배수
the multiple of n
수 num
과 n
이 매개 변수로 주어질 때
Integers num
and n
are given as parameters,
num
이 n
의 배수이면 1을 return
return 1 if num
is a multiple of n
n
의 배수가 아니라면 0을 return하도록 solution 함수를 완성해주세요.
and return 0 if it is not to complete the solution
function.
제한사항 (constraints):
The constraints section of the challenge informs us that num
can have values ranging from 2 to 100, and that n
can have values ranging from 2 to 9.
입출력 예 (input-output examples):
#1: When num
= 98 and n
= 1 the result should be 1.
#2: When num
= 32 and n
= 3 the result should be 0.
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
98은 2의 배수이므로 1을 return합니다.
It returns 1 because 98 is a multiple of 2.
Based on the example #2:
32는 3의 배수가 아니므로 0을 return합니다.
It returns 0 because 32 is not a multiple of 3.
JavaScript Solution
If we want to determine whether one number can be divided evenly by another, we have a few options in JavaScript. One popular way is to use an if...else
statement (if...else 조건문), which is a great fit for this problem.
To check whether num
is divisible by n
, we use the modulo operator %
to see if there is a remainder. If there is no remainder, we know that num
is divisible by n
and we return 1. If there is a remainder, we return 0.
Another approach is to use a ternary operator (삼항 연산자), which is a shorthand way to write the same code. This approach is shorter and more concise, which some developers might prefer.
// if... else solution
function solution(num, n) {
if (num % n === 0) {
return 1
} else {
return 0
}
}
// ternary operator solution
function solution(num, n) {
return (num % n === 0) ? 1 : 0
}
각도기
Description
각에서 0도 초과 90도 미만은 예각, 90도는 직각, 90도 초과 180도 미만은 둔각 180도는 평각으로 분류합니다. 각
angle
이 매개변수로 주어질 때 예각일 때 1, 직각일 때 2, 둔각일 때 3, 평각일 때 4를 return하도록 solution 함수를 완성해주세요.
예각 : 0 <
angle
< 90직각 :
angle
= 90둔각 : 90 <
angle
< 180평각 :
angle
= 180제한사항
0 <
angle
≤ 180
angle
은 정수입니다.입출력 예
angle result 70 1 91 3 180 4 입출력 예 설명
입출력 예 #1
angle
이 70이므로 예각입니다. 따라서 1을 return합니다.입출력 예 #2
angle
이 91이므로 둔각입니다. 따라서 3을 return합니다.입출력 예 #2
angle
이 180이므로 평각입니다. 따라서 4를 return합니다.
Description:
각도기
Protractor
각에서 0도 초과 90도 미만은 예각,
An angle greater than 0 degrees and less than 90 degrees is an acute angle,
90도는 직각,
90 degrees is a right angle,
90도 초과 180도 미만은 둔각
greater than 90 degrees and less than 180 degrees is an obtuse angle,
180도는 평각으로 분류합니다.
and an angle equal to 180 degrees is a straight angle.
각 angle
이 매개변수로 주어질 때
When angle
is given as a parameter, return
예각일 때 1,
1 for an acute angle,
직각일 때 2,
2 for a right angle,
둔각일 때 3,
3 for an obtuse angle,
평각일 때 4를 return하도록 solution 함수를 완성해주세요.
and 4 for a straight angle to complete the solution
function.
예각 : 0 < angle
< 90
acute angle: 0 < angle
< 90
직각 : angle
= 90
right angle: angle
= 90
둔각: 90 < angle
< 180
obtuse angle: 90 < angle
< 180
평각 : angle
= 180
straight angle: angle
= 180
제한사항 (constraints):
The constraints section of the challenge informs us that angle
is an integer (정수) and it can have values ranging from 0 to 180.
입출력 예 (input-output examples):
#1: When angle
= 70 the result should be 1.
#2: When angle
= 91 the result should be 3.
#3: When angle
= 180 the result should be 4.
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
angle
이 70이므로 예각입니다. 따라서 1을 return합니다.
Since angle
is 70, it is an acute angle. So it returns 1.
Based on the example #2:
angle
이 91이므로 둔각입니다. 따라서 3을 return합니다.
Since angle
is 91, it is an obtuse angle. So it returns 3.
Based on the example #3:
angle
이 180이므로 평각입니다. 따라서 4를 return합니다.
Since angle
is 180, it is a straight angle. So it returns 4.
JavaScript Solution
Here we will need two more else if
statements added to our if... else
statement. We also need to make sure we use relational operators (관계연 산자) correctly.
This can be also solved in two ways, more or less descriptive. The edge cases will also be handled differently.
The first solution provides more specific information on how the function is handling different angles within the range of 0 to 180. It breaks down the range into four distinct cases, including angles between 0 and 90, 90, angles between 90 and 180, and 180. This approach allows for more precise identification of the angle's location and how it's being handled, which can make debugging and maintenance easier in the long run.
The second solution is more concise and combines the second and fourth cases, resulting in only three cases. While this approach is still functional, it is slightly less descriptive because it doesn't provide as much information about how the function is handling different angles. As a result, it may be less clear to other developers or maintainers who are reading or working with the code.
Overall, the choice between these solutions comes down to a balance between the need for precise information and the desire for simplicity and conciseness. In general, it's best to strive for a balance between these two factors, creating code that is both readable and efficient.
// #1: more descriptive solution
function solution(angle) {
if(0 < angle && angle < 90) return 1
else if (angle === 90) return 2
else if (90 < angle && angle < 180) return 3
else if (angle === 180) return 4
else return
}
// #2: a slightly less descriptive solution
function solution(angle) {
if(0 < angle && angle < 90) return 1
else if (angle === 90) return 2
else if (90 < angle && angle < 180) return 3
else return 4
}
숫자 비교하기
Description
정수
num1
과num2
가 매개변수로 주어집니다. 두 수가 같으면 1 다르면 -1을 return하도록 solution 함수를 완성해주세요.제한사항
0 ≤
num1
≤ 10,0000 ≤
num2
≤ 10,000입출력 예
num1 num2 result 2 3 -1 11 11 1 7 99 -1 입출력 예 설명
입출력 예 설명 #1
num1
이 2이고num2
가 3이므로 다릅니다. 따라서 -1을 return합니다.입출력 예 설명 #2
num1
이 11이고num2
가 11이므로 같습니다. 따라서 1을 return합니다.입출력 예 설명 #3
num1
이 7이고num2
가 99이므로 다릅니다. 따라서 -1을 return합니다.
Description:
숫자 비교하기
Comparing numbers
정수 num1
과 num2
가 매개변수로 주어집니다.
Integers num1
and num2
are given as parameters.
두 수가 같으면 1 다르면 -1을 return하도록 solution 함수를 완성해주세요.
Complete the solution
function to return 1 if the two numbers are the same and -1 if they are different.
제한사항 (constraints):
The constraints section of the challenge informs us that both num1
and num2
can have values ranging from 0 to 10,000.
입출력 예 (input-output examples):
#1: When num1
= 2 and num2
= 3 the result should be -1.
#2: When num1
= 11 and num2
= 11 the result should be 1.
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
num1
이 2이고 num2
가 3이므로 다릅니다. 따라서 -1을 return합니다.
Return -1 because num1
is 2 and num2
is 3, which means they are not equal.
Based on the example #2:
num1
이 11이고 num2
가 11이므로 같습니다. 따라서 1을 return합니다.
Return 1 because num1
is 11 and num2
is 11, which means they are equal.
JavaScript Solution
When it comes to comparing two numbers in JavaScript, we have a couple of options. We can use an if...else
statement (if...else
조건문) or a ternary operator (삼항 연산자). Both of these methods will work just fine.
One important thing to keep in mind is that we want to use a strict equality operator ===
(일치 연산자) to compare the numbers. This ensures that we are comparing the numbers' values and types, so we don't run into any unexpected issues.
// if... else solution
function solution(num1, num2) {
if (num1 === num2) {
return 1
} else {
return -1
}
}
// ternary operator solution
function solution(num1, num2) {
return (num1 === num2) ? 1 : -1
}
옷가게 할인 받기
Description
머쓱이네 옷가게는 10만 원 이상 사면 5%, 30만 원 이상 사면 10%, 50만 원 이상 사면 20%를 할인해줍니다.
구매한 옷의 가격price
가 주어질 때, 지불해야 할 금액을 return 하도록 solution 함수를 완성해보세요.제한사항
10 ≤
price
≤ 1,000,000
price
는 10원 단위로(1의 자리가 0) 주어집니다.소수점 이하를 버린 정수를 return합니다.
입출력 예
price result 150,000 142,500 580,000 464,000 입출력 예 설명
입출력 예 #1
- 150,000원에서 5%를 할인한 142,500원을 return 합니다.
입출력 예 #2
- 580,000원에서 20%를 할인한 464,000원을 return 합니다.
Description:
옷가게 할인 받기
Clothing store discount
머쓱이네 옷가게는 10만 원 이상 사면 5%,
If 머쓱이 spends more than 100,000 won in the clothing store, a 5% discount is given.
30만 원 이상 사면 10%,
A 10% discount is given above 300,000 won,
50만 원 이상 사면 20%를 할인해줍니다.
and a 20% discount is given above 500,000 won.
구매한 옷의 가격 price
가 주어질 때,
Given the price
,
지불해야 할 금액을 return 하도록 solution 함수를 완성해보세요.
return the discounted price to complete the solution
function.
제한사항 (constraints):
The constraints section of the challenge informs us that price
can have values ranging from 10 to 1,000,000.
price
는 10원 단위로(1의 자리가 0) 주어집니다.
price
is given in increments of 10 won (starting from 0).
소수점 이하를 버린 정수를 return합니다.
Returns an integer without the decimal point. (10000 not 10,000)
입출력 예 (input-output examples):
#1: When price
= 150,000 the result should be 142,500.
#2: When price
= 580,000 the result should be 464,000.
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
150,000원에서 5%를 할인한 142,500원을 return 합니다.
Returns 142,500 won, which is a 5% discount from 150,000 won.
Based on the example #2:
580,000원에서 20%를 할인한 464,000원을 return 합니다.
Returns 464,000 won, a 20% discount from 580,000 won.
JavaScript Solution
With this example, let's talk about when to use ternary operators (삼항 연산자) versus if...else
statements (if...else
조건문).
In this example, we apply discounts based on the original price in three different ranges. If the price falls within a certain range, a discount percentage is applied to it, and we get a new discounted price:
If
price
is between 100,000 and 299,999, the discount applied is 5% and the new discounted price is calculated by multiplyingprice
by 0.95.If
price
is between 300,000 and 499,999, the discount applied is 10% and the new discounted price is calculated by multiplyingprice
by 0.9.If
price
is greater than or equal to 500,000, the discount applied is 20% and the new discounted price is calculated by multiplyingprice
by 0.8.If
price
is less than 100,000, no discount is applied and the original price is returned.
At the end of the function, we also have to use the Math.floor()
method to round down the discounted price to the nearest whole number.
We can write this function using an if...else
statement (if...else
조건문), which is easy to read and understand. However, if we try to use a ternary operator (삼항 연산자) to write this function, we will need to chain multiple ternary operators together, resulting in a long and hard-to-read code (Have you ever heard of spaghetti code?).
// if... else statement solution
function solution(price) {
let discount = 0
if (price >= 100000 && price < 300000) {
discount = price * 0.95
} else if (price >= 300000 && price < 500000) {
discount = price * 0.9
} else if (price >= 500000) {
discount = price * 0.8
} else {
discount = price
}
return Math.floor(discount)
}
// ternary operator solution
function solution(price) {
let discount = (price >= 100000 && price < 300000) ? price * 0.95 : (price >= 300000 && price < 500000) ? price * 0.9 : (price >= 500000) ? price * 0.8 : price
return Math.floor(discount)
}
Wrap-up
Congratulations, you did it! 머쓱이 and I are both incredibly proud of you!
By learning the important vocabulary related to else...if statements, logical operators, and ternary operators, you've taken another step forward towards fluency in technical Korean.
And if you want to support this series and the work I put into it, you can do it by buying me a coffee here:
%%[bmc]
Thanks!
I hope you have an amazing weekend, and I look forward to seeing you next week!
Top comments (0)