30 Days Of JavaScript.4
Day 4. Conditionals
On
Day 4
, I learned about various conditionals. I think setting the conditions is most important in solving a task. Doing exercises really helped out knowing what I missed. Let’s start!
Conditionals
The statements in JavaSrcipt script are executed sequentially from top to bottom. But it can be changed in two ways:
- conditional execution: if certain execution is true
- repetitive execution: as long as a certain expression is true
1. IF
if (condition) {
//block code that runs for truthy condition;
};
In this case, if the condition is false, I cannot get any results.
2. IF. ELSE
if (condition) {
//code runned for truthy condition;
} else {
//code runned for false condition;
};
3. If. ELSE IF. ELSE
if (condition0) {
//code when condition0 is true;
} else if (condition1) {
//code when condition1 is true;
} else (condition2) {
//code with condition2 is true;
};
I can add more than one else if
s if there are multiple conditions.
4. Switch
switch (caseValue) {
case '1':
//code;
break; //to terminate the execution
case '2':
//code;
break;
default:
//code;
};
Again, I can put as many cases that I want to before the default(I think default
is similar to else
. The remainders.).
The default block runs if all the cases don’t satisfy the condition. So it doesn’t need a
break;
to terminate the execution.
The
caseValue
above will be compared to the case, the position of ‘1’. If the type of variable and value are the same, it’s fine. But if I want to put a condition to a case, thecaseValue
should be a Boolean, to make the comparison happen.
5. Ternary Operator
condition
? //execution for truth
: //execution for false;
💡Exercise
👟Level 1.
1) Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:’You are old enough to drive’ but if not 18 give another feedback stating to wait for the number of years he needs to turn 18.
let ageUserInput = prompt("Enter your age.");
if (ageUserInput >= 18) {
console.log('You are old enough to drive.')
} else {
console.log(`You are left with ${18-ageUserInput} years to drive.`)
};
2) Compare the values of myAge and yourAge using if … else. Based on the comparison and log the result to console stating who is older (me or you). Use prompt(“Enter your age:”) to get the age as input.
let myAge = 23;
let yourAgeInput = prompt("Enter your age.");
let diff = myAge - yourAgeInput;
if (diff > 0) {
console.log(`I am ${diff} years older than you.`)
} else if (diff < 0) {
console.log(`You are ${Math.abs(diff)} years older than me.`)
} else {
console.log('You have the same age as me.')
};
3) If a is greater than b return ‘a is greater than b’ else ‘a is less than b’. Try to implement it in two ways.
- using
if else
let a = prompt('Enter a number.');
let b = prompt('Enter another number.');
if (a > b) {
console.log('a is greater than b.')
} else if (a < b) {
console.log('a is less than b.')
};
I cannot use else
with following parenthesis. It will give me an error. Think of else
as a remainder of all conditions. If I want to add more conditions, I should use else if()
.
Also, in this case, if I didn’t set the condition for the case of a == b
. If the user inputs the same number, the result will be undefined
. If I want to get another output for that, I can simply add else
below.
let a = prompt('Enter a number.');
let b = prompt('Enter another number.');
if (a > b) {
console.log('a is greater than b.')
} else if (a < b) {
console.log('a is less than b.')
} else {
console.log('a is same as b.')
};
- using
ternary operator
let a = prompt('Enter a number.');
let b = prompt('Enter another number.');
a > b
? console.log('a is greater than b.')
: console.log('a is less than b.');
However, in this case, the code will give the result ‘a is less than b.’ if a and b are the same. This is because the ternary operator doesn’t seperate the cases specifically like if else
. If a > b
is not true, the code with : will be executed.
4) Even numbers are divisible by 2 and the remainder is zero. How do you check, if a number is even or not using JavaScript?
let numberInput = prompt('Enter a number.');
numberInput % 2 == 0
? console.log(`${numberInput} is an even number.`)
: console.log(`${numberInput} is an odd number.`);
The syntax for the modulus operator(%) is (number_one % number_two)
👟Level 2.
1) Write a code which can give grades to students according to theirs scores:
90-100, A / 70-89, B / 60-69, C / 50-59, D / 0-49, F
let score = prompt('Enter number');
switch (true) {
case score >= 90:
console.log('A');
break;
case score >= 70:
console.log('B');
break;
case score >= 60:
console.log('C');
break;
case score >= 50:
console.log('D');
break;
default:
console.log('F');
};
There were multiple ranges of grades, so I chose to use the switch operator. But I had a hard time setting the cases. At first, I set the cases like 90 <= score < 100
, but somehow the results were always A or F(default) regardless of the value I put in. I first thought ‘maybe the prompt is returning a string, so I have to change the variable to Number(prompt('Enter number.'))
’ but it didn’t work. switch(score)
didn’t work either. I figured out true
should be inside the parenthesis just by copying the example code on the file.
Then I came up with the idea that I don’t need to set the highest value. The code will automatically run from top to bottom, so the lowest value was all I needed. If the score is higher than that, it will execute. If not, it’ll run down below.
About the (true)
, I googled it and found the answer in stackoverflow. The value inside the parenthesis will be compared to what the case returns. score >= 90
returns true or false, but none of it matches with score
, which is a number. So if the score value were a string, switch(score) {case 'orange': ... }
would work, because it can be compared, having a same type. That’s why I should put ‘true’ in the parenthesis. It would mean ‘if score >= 90
is true
, then execute’.
x >= 5 and x < 5 are going to give you true or false, which x will then be compared to. Since x will always be a number, it will never be true or false so you will always hit the default.
I also tried the if else
operator with this one.
let score = prompt('Enter your score.');
if (90 <= score) {
console.log('A');
} else if (70 <= score) {
console.log('B');
} else if (60 <= score) {
console.log('C');
} else if (50 <= score) {
console.log('D');
} else {
console.log('F');
};
Doing this, I found out that 90 <= score < 100
just doesn’t work. Instead, I have to put it in 90 <= score && score < 100
form with ampersand operator(&&
). Remember, we have to explain kindly and specifically to a computer.
let score = prompt('Enter your score.');
if (90 <= score && score < 100) {
console.log('A');
} else if (70 <= score && score < 90) {
console.log('B');
} else if (60 <= score && score < 70) {
console.log('C');
} else if (50 <= score && score < 60) {
console.log('D');
} else {
console.log('F');
};
3) Check if the season is Autumn, Winter, Spring or Summer. If the user input is :
September, October or November, the season is Autumn. December, January or February, the season is Winter. March, April or May, the season is Spring. June, July or August, the season is Summer.
I first approached it with a pipe operator, and it only wored with the first case(march, june, september, december). It didn’t work with the following inputs.
let seasonInput = prompt('What month is it now?');
let season = seasonInput.toLowerCase();
switch (season) {
case 'march'||'april'||'may':
console.log('The season is Spring.');
break;
case 'june'||'july'||'august':
console.log('The season is Summer.');
break;
case 'september'||'october'||'november':
console.log('The season is Autumn.');
break;
case 'december'||'january'||'february':
console.log('The season is Winter.');
break;
};
Finding more about assigning multiple cases, I found that there’s a fall-through feature of the switch statement, which I used in my second answer. In a fall-through feature, a matched case will run until a break (or the end of the switch statement) is found, so I can put many cases before the break
comes.
let seasonInput = prompt('What month is it now?');
let season = seasonInput.toLowerCase();
switch (season) {
case 'march':
case 'april':
case 'may':
console.log('The season is Spring.');
break;
case 'june':
case 'july':
case 'august':
console.log('The season is Summer.');
break;
case 'september':
case 'october':
case 'november':
console.log('The season is Autumn.');
break;
case 'december':
case 'january':
case 'february':
console.log('The season is Winter.');
break;
};
Use
toLowerCase()
to make the inputs case-insensitive!
4) Check if a day is weekend day or a working day. Your script will take day as an input.
What is the day today? Saturday
Saturday is a weekend.
What is the day today? saturDaY
Saturday is a weekend.
What is the day today? Friday
Friday is a working day.
What is the day today? FrIDAy
Friday is a working day.
In this case, I should uppercase the first letter, and lowercase the rest. At first I tried uppercasing the first letter using string, but I didn’t have any idea how I should treat other letters. I searched stackoverflow and found out that I could use slice()
method. From the things I’ve learned, I think the substring()
is the nearest thing to slice()
. It did its job too.
Another part that made me struggle is the displaying part. I first tried 'dayInput[0].toUpperCase()'+'dayInput.slice(1).toLowerCase'
but the result was undefined
. Then I tried to use concat()
(dayInput.concat('dayInput[0].toUpperCase()','dayInput.slice(1).toLowerCase');
) but it wouldn’t work either. I searched again, and found out that I should use the template literals(or string interpolation method) like below.
let dayInput = prompt('What day is it today?');
let day = `${dayInput[0].toUpperCase()}${dayInput.slice(1).toLowerCase()}`
/*
substring(1) in the place of slice(1) would also work
They both select from the second letter of a word to the end.
*/
switch (day) {
case 'Saturday':
case 'Sunday':
console.log(`${day} is a weekend.`);
break;
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
console.log(`${day} is a working day.`);
break;
};
To only capitalize the first letter of a word, first split a word with
slice()
orsubstring()
. Then usetoUpperCase()
andtoLowerCase()
.
Using a string template(string interpolation method), I can add expressions in the string. Expressions could be a value, or some operations(comparison, arithmetic operation, or ternary operation).
👟Level 3.
1) Write a program which tells the number of days in a month.
Enter a month: January
January has 31 days.
Enter a month: JANUARY
January has 31 day
Enter a month: February
February has 28 days.
Enter a month: FEbruary
February has 28 days.
In this case, I should capitalize the user input of month and also case the inputs down to 3(having 28, 30, or 31 days). I used default in the end to make the code more readable, but for the accuary I can specify all the months too.
let monthInput = prompt('What month is it now?');
let month = `${monthInput[0].toUpperCase()}${monthInput.substring(1).toLowerCase()}`;
switch (month) {
case 'February':
console.log(`${month} has 28 days.`);
break;
case 'April' || 'June' || 'September' || 'November':
console.log(`${month} has 30 days.`);
break;
default:
console.log(`${month} has 31 days.`);
break;
};
Don’t forget to add back-ticks(``) when using string template expressions(${ })!
2) Write a program which tells the number of days in a month, now consider leap year.
In the leap year, February has 29 days. Leap year can be identified by two ways.
- the number of the year should be divisible by 4, but not divisible by 100.
- the number of the year should be divisible by both 400.
From these, I could use an if
condition.
let yearInput = prompt('What year is it now?');
let monthInput = prompt('What month is it now?');
let month = `${monthInput[0].toUpperCase()}${monthInput.substring(1).toLowerCase()}`;
if (((yearInput%4 == 0) && (yearInput%100 != 0)) || (yearInput%400 == 0)) {
switch (month) {
case 'February':
console.log(`${month} has 29 days.`);
break;
case 'April' || 'June' || 'September' || 'November':
console.log(`${month} has 30 days.`);
break;
default:
console.log(`${month} has 31 days.`);
break;
};
} else {
switch (month) {
case 'February':
console.log(`${month} has 28 days.`);
break;
case 'April' || 'June' || 'September' || 'November':
console.log(`${month} has 30 days.`);
break;
default:
console.log(`${month} has 31 days.`);
break;
};
};
I used if else
condition operator, and it worked. I thought about making the code shorter, by only specifying the case of February. But getting condition more complicated actually made the code longer. If you have any idea on this, the comment section below is always open!
Leave a comment