Conditionals and Loop
Chapter: 14
The If statement
The if Statement
Well done! You’re making great progress. On to module 3!
Often when we write code, we want to perform different actions based on different conditions.
And this is where conditional statements come in.
There are a bunch of different conditionals, to cover, but we’re starting with one of the most useful: "if"
We use if to specify a block of code that we want to be executed if a specified condition is true.
if (condition) {
statements
}
statements
}
JS
var myNum1 = 7;
var myNum2 = 10;
if (myNum1 < myNum2) {
alert("JavaScript is easy to learn.");
}
var myNum2 = 10;
if (myNum1 < myNum2) {
alert("JavaScript is easy to learn.");
}
JS
Heads up!
You can see from the example above, we’ve used the JavaScript alert() to generate a popup alert box that contains the information inside the parentheses.
You can see from the example above, we’ve used the JavaScript alert() to generate a popup alert box that contains the information inside the parentheses.
The if Statement
Add the characters that complete the statement:
The if Statement
Here’s a little more detail on the if statement.
This is an example of a false conditional statement:
var myNum1 = 7;
var myNum2 = 10;
if (myNum1 > myNum2) {
alert("JavaScript is easy to learn.");
}
var myNum2 = 10;
if (myNum1 > myNum2) {
alert("JavaScript is easy to learn.");
}
JS
Heads up!
if is in lowercase letters. Uppercase letters (If or IF) won’t work.
if is in lowercase letters. Uppercase letters (If or IF) won’t work.
The if Statement
What happens if the tested condition is false?
Practice:
The if Statement
You are planning a vacation in August.
You are given a program that takes the month as input.
Task
Complete the code to output "vacation", if the given month is August. Don't output anything otherwise.
Sample Input
August
Sample Output
vacation
Note: Comment down your answer
Handle the required condition using an if statement.
Use console.log() for the output.
Use console.log() for the output.
Chapter: 15
The Else statement
The else Statement
Right, so we’ve seen that the action gets skipped when a code block using the if statement evaluates to false, but what if we want something else to happen.
Well, we use the "else" statement, of course!
We can use the else statement to specify a block of code that will execute if the condition is false. Like this:
if (expression) {
// executed if condition is true
}
else {
// executed if condition is false
}
// executed if condition is true
}
else {
// executed if condition is false
}
JS
Heads up!
You can skip the curly braces if the code under the condition contains only one command.
You can skip the curly braces if the code under the condition contains only one command.
The else Statement
The "else" statement is created to do what?
The else Statement
Here’s another example of the if and else statements working together:
var myNum1 = 7;
var myNum2 = 10;
if (myNum1 > myNum2) {
alert("This is my first condition");
}
else {
alert("This is my second condition");
}
var myNum2 = 10;
if (myNum1 > myNum2) {
alert("This is my first condition");
}
else {
alert("This is my second condition");
}
JS
- If myNum1 is greater than myNum2, alert "This is my first condition";
- Else, alert "This is my second condition".
So the browser will print out the second condition, as 7 is not greater than 10.
Heads up!
There's another way to do this check using the ? operator: a > b ? alert(a) : alert(b).
There's another way to do this check using the ? operator: a > b ? alert(a) : alert(b).
The else Statement
Fill in the blanks to create a valid if...else statement:
Practice:
The if else statement
The current world record for high jumping is 2.45 meters.
You are given a program that receives as input a number that represents the height of the jump.
Task
Complete the code to:
1. output to the console "new record" if the number is more than 2.45,
2. output to the console "not this time" in other cases.
Sample Input
2.49
Sample Output
new record
Note that if the jump height is equal to 2.45 meters, it's not a new world record.
Chapter: 16
The Else If statement
else if
We've seen else, we've seen if, time to meet else if.
The else if statement is useful because it lets us specify a new condition if the first condition is false.
Like this:
var course = 1;
if (course == 1) {
document.write("<h1>HTML Tutorial</h1>");
} else if (course == 2) {
document.write("<h1>CSS Tutorial</h1>");
} else {
document.write("<h1>JavaScript Tutorial</h1>");
}
if (course == 1) {
document.write("<h1>HTML Tutorial</h1>");
} else if (course == 2) {
document.write("<h1>CSS Tutorial</h1>");
} else {
document.write("<h1>JavaScript Tutorial</h1>");
}
JS
- if course is equal to 1, output "HTML Tutorial";
- else, if course is equal to 2, output "CSS Tutorial";
- if none of the above condition is true, then output "JavaScript Tutorial";
course is equal to 1, so we get the following result:
Heads Up!
The final else statement "ends" the else if statement and should be always written after the if and else if statements.
The final else statement "ends" the else if statement and should be always written after the if and else if statements.
else if
What keyword is used to end the "else if" statement?
else if
The final else block will be executed when none of the conditions is true.
Let's change the value of the course variable in our previous example.
var course = 3;
if (course == 1) {
document.write("<h1>HTML Tutorial</h1>");
} else if (course == 2) {
document.write("<h1>CSS Tutorial</h1>");
} else {
document.write("<h1>JavaScript Tutorial</h1>");
}
if (course == 1) {
document.write("<h1>HTML Tutorial</h1>");
} else if (course == 2) {
document.write("<h1>CSS Tutorial</h1>");
} else {
document.write("<h1>JavaScript Tutorial</h1>");
}
JS
You can write as many else if statements as you need.
else if
Fill in the blanks to create a valid if...else...if statement:
Practice:
else if
Тhe result of an exam will be determined as follows։
If the score is
88 and above => excellent
40-87 => good
0-39 => fail
You are given a program that takes the score as input.
Task
Complete the code to output the corresponding result (excellent, good, fail) to the console.
Sample Input
78
Sample Output
good
Use console.log() to output the result to the console.
Use logical operator && to chain multiple conditions.
Use logical operator && to chain multiple conditions.
Chapter: 17
The Switch Statement
Switch
But what if you need to test for multiple conditions? In those cases, writing if else statements for each condition might not be the best solution.
Instead, we can use the switch statement to perform different actions based on different conditions.
Here's what that looks like:
switch (expression) {
case n1:
statements
break;
case n2:
statements
break;
default:
statements
}
case n1:
statements
break;
case n2:
statements
break;
default:
statements
}
JS
Heads up!
You can achieve the same result with multiple if...else statements, but the switch statement is more effective in such situations.
You can achieve the same result with multiple if...else statements, but the switch statement is more effective in such situations.
Switch
The switch statement can be used to replace…
The switch Statement
Let's look at another example:
var day = 2;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
JS
Heads up!
You can have as many case statements as you need.
You can have as many case statements as you need.
The switch Statement
How many "case" statements are usually used in the "switch" statement?
The break Keyword
So we have learned that the switch statement tests a code block, but we won't always want it to test the whole block. The break keyword essentially switches the switch statement off.
Breaking out of the switch block stops the execution of more code and case testing inside the block.
Heads up!
Usually, a break should be put in each case statement.
Usually, a break should be put in each case statement.
The break Keyword
What’s the output of this code? var x = 3; switch (x) { case 1: document.write(x); break; case 2: document.write(x+2); break; default: document.write(x+5); }
The default Keyword
Often there will be no match, but we still need the program to output something...for this we use the default keyword, which specifies the code to run if there’s no case match.
Like this:
var color ="yellow";
switch(color) {
case "blue":
document.write("This is blue.");
break;
case "red":
document.write("This is red.");
break;
case "green":
document.write("This is green.");
break;
case "orange":
document.write("This is orange.");
break;
default:
document.write("Color not found.");
}
switch(color) {
case "blue":
document.write("This is blue.");
break;
case "red":
document.write("This is red.");
break;
case "green":
document.write("This is green.");
break;
case "orange":
document.write("This is orange.");
break;
default:
document.write("Color not found.");
}
JS
Heads up!
The default block can be omitted, if there is no need to handle the case when no match is found.
The default block can be omitted, if there is no need to handle the case when no match is found.
The default Keyword
The "default" statement is used …
Practice:
Q. Stone, Paper and Cissor Game
Hint:
Make a stone paper Cissor game with the help of else , if and switch statements.
Make a stone paper Cissor game with the help of else , if and switch statements.
Chapter: 18
For-loop Statement
Loops
Loops can execute a block of code a number of times. They’re handy when you want to run the same code repeatedly, adding a different value each time.
JavaScript has three types of loops: for, while, and do while.
We’ll start here with the classic for loop.
Here's the syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}
code block to be executed
}
JS
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
Heads up!
As you can see, the classic for loop has three components, or statements.
As you can see, the classic for loop has three components, or statements.
Loops
The classic "for" loop consists of how many components?
The For Loop
Now we've got the theory, let's look at a specific example.
This example creates a for loop that prints numbers 1 through 5:.
for (i=1; i<=5 i++) {
document.write(i + "<br />");
}
document.write(i + "<br />");
}
JS
In this example, Statement 1 sets a variable before the loop starts (var i = 1).
Statement 2 defines the condition for the loop to run (it must be less than or equal to 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Result:
var i = 1;
for (; i<=5; i++) {
document.write(i + "<br />");
}
for (; i<=5; i++) {
document.write(i + "<br />");
}
JS
You can also initiate more than one value in statement 1, using commas to separate them.
for (i=1, text=""; i<=5; i++) {
text = i;
document.write(i + "<br />");
}
text = i;
document.write(i + "<br />");
}
JS
Heads up!
ES6 introduces other for loop types; you can learn about them in the ES6 course later.
ES6 introduces other for loop types; you can learn about them in the ES6 course later.
The For Loop
Fill in the blanks to compose a valid for loop:
The For Loop
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
Statement 2 is also optional, but only if you put a break inside the loop. Otherwise, the loop will never end!
Statement 3 is used to change the initial variable. It can do anything, including negative increment (i--), positive increment (i = i + 15).
Statement 3 is also optional, but only if you increment your values inside the loop. Like this:
var i = 0;
for (; i < 10; ) {
document.write(i);
i++;
}
for (; i < 10; ) {
document.write(i);
i++;
}
JS
Heads up!
You can have multiple nested for loops.
You can have multiple nested for loops.
Practice:
Q. Making "*" pattern
Pattern: *****
****
***
**
*
Note: Make star pattern by using for loop and comment down your answer.
Chapter: 19
While Loop
Time to move on to the second of our three loop statements, while.
The while loop repeats through a block of code, but only as long as a specified condition is true.
Here's the syntax:
The while loop repeats through a block of code, but only as long as a specified condition is true.
Here's the syntax:
while (condition) {
code block
}
code block
}
JS
Heads up!
The condition can be any conditional statement that returns true or false.
The condition can be any conditional statement that returns true or false.
The While Loop
The result of the condition statement is always:
The While Loop
Ok, we've got the theory, let's look at a real example:
var i=0;
while (i<=10) {
document.write(i + "<br />");
i++;
}
while (i<=10) {
document.write(i + "<br />");
i++;
}
JS
This will output the values from 0 to 10.
Heads up!
Be careful when writing conditions. If a condition is always true, the loop will run forever!
Be careful when writing conditions. If a condition is always true, the loop will run forever!
The While Loop
Endless loops are not good. And one way of this happening is if we forget to increase the variable used in the condition.
Heads up!
Make sure that the condition in a while loop eventually becomes false.
Make sure that the condition in a while loop eventually becomes false.
The While Loop
How many times will the while loop run, if we remove the counting variable increment statement?
Practice:
Q. Making "*" pattern
Pattern: *****
****
***
**
*
Note: Make star pattern by using while loop and comment down your answer.
Chapter: 20
Do..While Loop
The Do...While Loop
Almost done with loops! You're doing great!
The last loop we’re looking at in this module is the do...while loop, it's a variant of the while loop but with one important difference.
This loop will execute the code block once, before checking if the condition is true, and then it will repeat the loop as long as the condition is true.
Here’s the Syntax:
do {
code block
}
while (condition);
code block
}
while (condition);
JS
Heads up!
Note the semicolon used at the end of the do...while loop. This is important.
Note the semicolon used at the end of the do...while loop. This is important.
var i=20;
do {
document.write(i + "<br />");
i++;
}
while (i<=25);
do {
document.write(i + "<br />");
i++;
}
while (i<=25);
JS
Heads up!
The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.
The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.
The Do...While Loop
Apply the "do" and "while" keywords in their corresponding positions.
Chapter: 21
Break and Continue
Break
We've met the break statement earlier in this module, we use it to "jump out" of a loop and continue executing the code after the loop.
Like this:
for (i = 0; i <= 10; i++) {
if (i == 5) {
break;
}
document.write(i + "<br />");
}
if (i == 5) {
break;
}
document.write(i + "<br />");
}
JS
Heads up!
You can use the return keyword to return some value immediately from the loop inside of a function. This will also break the loop.
You can use the return keyword to return some value immediately from the loop inside of a function. This will also break the loop.
Continue
We're nearly done with module 3! One last thing to cover.
Unlike the break statement, the continue statement breaks only one iteration in the loop, and continues with the next iteration.
Like this:
for (i = 0; i <= 10; i++) {
if (i == 5) {
continue;
}
document.write(i + "<br />");
}
if (i == 5) {
continue;
}
document.write(i + "<br />");
}
JS
Heads up!
The value 5 is not printed, because continue skips that iteration of the loop.
The value 5 is not printed, because continue skips that iteration of the loop.
Chapter: 22
Module 3 Quiz
Q1.What’s the output of this code? var x = 0; while(x<6) { x++; } document.write(x);
Fill in the right keywords to test the conditions:
Chapter: 23
Code Project: The snail is the well
The Snail in the Well
The snail climbs up 7 feet each day and slips back 2 feet each night.
How many days will it take the snail to get out of a well with the given depth?
Sample Input:
31
Sample Output:
6
Explanation: Let's break down the distance the snail covers each day:
Day 1: 7-2=5
Day 2: 5+7-2=10
Day 3: 10+7-2=15
Day 4: 15+7-2=20
Day 5: 20+7-2=25
Day 6: 25+7=32
So, on Day 6 the snail will reach 32 feet and get out of the well at day, without slipping back that night.
Note: Comment down your answer.
Hint: You can use a loop to calculate the distance the snail covers each day, and break the loop when it reaches the desired distance.





Comments
Post a Comment