Conditional Statements and Loops
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Introduction to Conditional Statements
Introduction to Conditional Statements
Conditional statements are used in programming to make decisions based on certain conditions. They allow us to control the flow of the program and execute specific statements or blocks of code based on whether a condition is true or false.
In JavaScript, the most common conditional statement is the if statement. It allows you to specify a condition inside parentheses, and if that condition evaluates to true, the code block inside the curly braces will be executed. Here's an example:
// Using an if statement to check if a number is positive
const number = 5;
if (number > 0) {
console.log('The number is positive');
}
In this example, we check if the number variable is greater than 0. If it is, we print a message to the console saying that the number is positive.
Conditional statements are the building blocks of decision-making in programming and are essential for creating dynamic and interactive applications. In the upcoming lessons, we will explore different types of conditional statements and learn how to use them effectively.
```javascript
// Example code
// Using an if statement to check if a number is positive
const number = 5;
if (number > 0) {
console.log('The number is positive');
}
```
True or False
The if statement is used to make decisions based on certain conditions.
If Statements
The if statement is a fundamental control structure in JavaScript that allows us to make decisions based on a condition. It is used to selectively execute a code block if the condition evaluates to true.
The basic syntax of an if statement is as follows:
if (condition) {
// code to execute if condition is true
}
Let's look at an example to understand how the if statement works:
const age = 25;
if (age >= 18) {
console.log('You are eligible to vote!');
}
In this example, we have a variable age with a value of 25. The if statement checks if the age is greater than or equal to 18. If the condition is true, the code block inside the curly braces will be executed and the message 'You are eligible to vote!' will be logged to the console.
The if statement can also be followed by an else statement to handle the case when the condition is false:
const num = 10;
if (num % 2 === 0) {
console.log('The number is even');
} else {
console.log('The number is odd');
}
In this example, we check if the num variable is divisible by 2. If the condition is true, the message 'The number is even' is logged to the console. Otherwise, the message 'The number is odd' is logged.
The if statement can also be used with multiple else if statements to handle multiple conditions:
const grade = 85;
if (grade >= 90) {
console.log('A');
} else if (grade >= 80) {
console.log('B');
} else if (grade >= 70) {
console.log('C');
} else if (grade >= 60) {
console.log('D');
} else {
console.log('F');
}
In this example, we check the value of the grade variable and log the corresponding letter grade based on the condition. If none of the conditions are true, the message 'F' is logged.
The if statement is a powerful tool for making decisions in JavaScript and is essential for writing conditional code.
True or False
The if statement is used to selectively execute a code block if a condition is true.
If-Else Statements
If-Else Statements
In JavaScript, the if-else statement is a control flow statement that allows you to handle alternative conditions. With if-else statements, you can define two blocks of code to be executed depending on whether a condition is true or false.
The basic syntax of an if-else statement is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Let's take an example to understand the usage of if-else statements. Imagine we have a variable age with a value of 25, and we want to check if the person is eligible to vote based on their age:
const age = 25;
if (age < 18) {
console.log('Sorry, you are not eligible to vote.');
} else {
console.log('You are eligible to vote!');
}
In this example, we first check if the age is less than 18. If the condition is true, the message 'Sorry, you are not eligible to vote.' will be logged to the console. If the condition is false, the code inside the else block will be executed, and the message 'You are eligible to vote!' will be logged.
The if-else statement is a powerful tool for handling alternative conditions in JavaScript. It allows your code to make different decisions based on different scenarios, providing flexibility and adaptability to your programs. You can have multiple else if blocks to handle more conditions if needed.
Try the following code snippet and observe the output:
const num = 10;
if (num % 2 === 0) {
console.log('The number is even');
} else {
console.log('The number is odd');
}
```javascript
const age = 25;
if (age < 18) {
console.log('Sorry, you are not eligible to vote.');
} else {
console.log('You are eligible to vote!');
}
```
If-Else Statements Fill In
In JavaScript, the if-else statement is used to handle alternative conditions. With if-else statements, you can define two blocks of code to be executed depending on whether a condition is true or false. The basic syntax of an if-else statement is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
In the context of conditional statements, the _____________ block is executed if the condition is false.
Nested If-Else Statements
Nested If-Else Statements
In JavaScript, nested if-else statements are used to handle complex conditions by combining multiple if-else statements. With nested if-else statements, you can have one if-else statement inside another if-else statement.
Nested if-else statements allow you to test for more specific conditions within the scope of a broader condition. This enables you to write logic that considers multiple factors.
Here's an example to illustrate nested if-else statements:
const age = 20;
const hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log('You are eligible to drive.');
} else {
console.log('You are eligible to apply for a license.');
}
} else {
console.log('You are not eligible to drive or apply for a license.');
}
In this example, we first check if the age is greater than or equal to 18. If it is, we then check if the hasLicense variable is true. Depending on the values of these variables, different messages will be logged to the console.
Nested if-else statements can be used to create more complex logic and handle multiple conditions in a program. They provide a way to evaluate different scenarios and execute specific blocks of code based on those scenarios.
Now it's your turn to practice using nested if-else statements. Feel free to modify the code example above and see how the output changes. You can also try creating your own nested if-else statements to solve different problems!
```javascript
// Example of nested if-else statements
const age = 20;
const hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log('You are eligible to drive.');
} else {
console.log('You are eligible to apply for a license.');
}
} else {
console.log('You are not eligible to drive or apply for a license.');
}
```
True or False
Nested if-else statements allow you to test for more specific conditions within the scope of a broader condition.
Switch Statements
Switch Statements
In JavaScript, a switch statement is used to perform different actions based on different conditions. It provides a concise way to handle multiple possible values of a variable.
When using switch statements, you specify an expression to be evaluated and a series of cases. Each case contains a value or multiple values that are compared to the expression. If there is a match, the corresponding block of code is executed.
Here's an example to illustrate the usage of a switch statement:
const day = 'Monday';
switch (day) {
case 'Monday':
console.log('It is the beginning of the week.');
break;
case 'Tuesday':
console.log('It is the second day of the week.');
break;
case 'Wednesday':
console.log('It is the middle of the week.');
break;
case 'Thursday':
case 'Friday':
console.log('It is almost the weekend.');
break;
default:
console.log('It is the weekend.');
}
In this example, the switch statement is used to determine the day of the week based on the value of the day variable. Depending on the value, a different message is logged to the console.
Switch statements are especially useful when you have a large number of possible conditions to check. Instead of writing multiple if-else statements, you can use a switch statement for a more concise and readable code.
Now it's your turn to practice using switch statements. Feel free to modify the code example above and see how the output changes. You can also try creating your own switch statements to solve different problems!
```javascript
const day = 'Monday';
switch (day) {
case 'Monday':
console.log('It is the beginning of the week.');
break;
case 'Tuesday':
console.log('It is the second day of the week.');
break;
case 'Wednesday':
console.log('It is the middle of the week.');
break;
case 'Thursday':
case 'Friday':
console.log('It is almost the weekend.');
break;
default:
console.log('It is the weekend.');
}
```
Switch Statements Multiple Choice
Which statement is true about switch statements in JavaScript?
Introduction to Loops
Introduction to Loops
Loops are an essential part of programming as they allow us to repeat a block of code multiple times. They are used when we need to perform a task repeatedly until a certain condition is met. Loops are particularly useful when dealing with collections of data or when we want to perform an operation a fixed number of times.
For example, imagine we have an array of numbers and we want to print each number on the console. Instead of manually writing a console.log statement for each number, we can use a loop to iterate through the array and print each value.
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
In this example, we use a for loop to iterate through the numbers array. The loop starts with an initialization step (let i = 0), a condition (i < numbers.length), and an increment step (i++). The loop continues as long as the condition is true and allows us to access each element of the array using the index i.
Loops provide a powerful mechanism for automating repetitive tasks and iterating over data structures. They are fundamental in many programming languages, including JavaScript.
Now it's your turn to practice using loops. Try writing a for loop to print the numbers from 1 to 10 on the console.
```javascript
// Let's log the numbers from 1 to 10 using a for loop
for (let i = 1; i <= 10; i++) {
console.log(i);
}
```
Introduction to Loops Fill In
A loop is used to _______ a block of code multiple times until a certain condition is met.
For Loops
For Loops
In JavaScript, a for loop is used to iterate over a collection of items, such as an array. It allows us to execute a block of code for each element in the collection.
A for loop consists of three parts:
- Initialization: Declare and initialize a loop variable, usually denoted as
i. - Condition: Specify the condition under which the loop will continue executing.
- Increment: Update the loop variable after each iteration.
Here's an example of using a for loop to iterate over an array of colors and print each color on the console:
// Iterating over an array using a for loop
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
In this example, we initialize the loop variable i to 0. Then, the loop continues executing as long as i is less than the length of the colors array. After each iteration, we increment i by 1. Inside the loop, we access each color using the index i and print it on the console.
For loops are commonly used when we need to perform a task a specific number of times or iterate over each element in a collection. They provide a convenient way to repeat a block of code based on a condition and help us automate repetitive tasks.
Now it's your turn to practice using a for loop. Try writing a for loop to iterate over an array of numbers and calculate their sum.
```javascript
// Iterating over an array using a for loop
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
```
For Loops Fill In
A for loop is used to iterate over a collection of items. It consists of three parts: initialization, condition, and _________________.
While Loops
While Loops
In JavaScript, a while loop is used to repeat a block of code while a certain condition is true. It allows us to continuously execute a set of statements until the condition becomes false.
Here's the basic syntax of a while loop:
while (condition) {
// code to be executed
}
The condition is evaluated before each iteration. If the condition is true, the code inside the loop is executed. Afterward, the condition is re-evaluated. If the condition is still true, the loop continues to iterate. If the condition is false, the loop stops, and the program continues with the next statement after the loop.
Here's an example that demonstrates the usage of a while loop:
let num = 1;
while (num <= 10) {
console.log(num);
num++;
}
In this example, we initialize the variable num with the value 1. The while loop continues to execute as long as num is less than or equal to 10. Inside the loop, we print the value of num and increment its value by 1 using the num++ statement.
While loops are useful when the number of iterations is not known in advance and depends on a condition. They allow us to repeatedly execute a block of code until a desired outcome is achieved.
Your turn to practice using a while loop! Try writing a while loop that prints the numbers from 1 to 10 in reverse order.
```javascript
// Example of a while loop
let count = 1;
while (count <= 5) {
console.log(`Count: ${count}`);
count++;
}
```
True or False
The condition of a while loop is evaluated before each iteration.
Do-While Loops
Do-While Loops
In JavaScript, a do-while loop is similar to a while loop, with one key difference. The code block inside a do-while loop is executed at least once, regardless of the condition. Then, the condition is checked at the end of each iteration. If the condition is true, the loop will continue to execute. If the condition is false, the loop will terminate.
The basic syntax of a do-while loop in JavaScript is as follows:
do {
// code to be executed
} while (condition);
Here's an example that demonstrates the usage of a do-while loop:
let x = 1;
do {
console.log(x);
x++;
} while (x <= 5);
In this example, the variable x is initialized with the value 1. The code block inside the do-while loop will be executed at least once, printing the value of x and incrementing its value by 1. The loop will continue to execute as long as x is less than or equal to 5.
Do-while loops are useful when you want to ensure that a certain code block is executed at least once before checking the condition. It can be particularly handy when you need to validate user input or perform an initial setup before entering a loop.
```js
// JavaScript code example
let x = 1;
do {
console.log(x);
x++;
} while (x <= 5);
```
Do-While Loops Multiple Choice
Which of the following statements about do-while loops in JavaScript is true?
Break and Continue Statements
Break and Continue Statements
In programming, there are situations where we need to control the execution of loops based on certain conditions. The break and continue statements allow us to have more control over the flow of loops.
The break Statement
The break statement is used to terminate the loop and exit its current iteration. When the break statement is encountered inside a loop, the loop is immediately terminated, and the program continues with the next statement after the loop.
Here's an example that demonstrates the usage of the break statement:
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
In this example, the loop will iterate from 1 to 10. However, when i becomes equal to 5, the break statement is executed, and the loop is terminated. As a result, only the numbers 1, 2, 3, and 4 will be logged to the console.
The break statement is useful when we want to exit a loop prematurely based on a certain condition.
The continue Statement
The continue statement is used to skip the rest of the current iteration and move on to the next iteration of the loop. When the continue statement is encountered inside a loop, the remaining statements inside the loop for that iteration are skipped, and the program continues with the next iteration.
Here's an example that demonstrates the usage of the continue statement:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
In this example, the loop will iterate from 1 to 10. However, when i is an even number (divisible by 2), the continue statement is executed, and the remaining statements inside the loop are skipped for that iteration. As a result, only the odd numbers 1, 3, 5, 7, and 9 will be logged to the console.
The continue statement is useful when we want to skip certain iterations of a loop based on a certain condition.
Both the break and continue statements provide us with more control over the flow of loops in JavaScript. They can be used to handle specific cases and make our code more efficient and readable.
```js
// replace with js logic relevant to content
// make sure to log something
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('FizzBuzz');
} else if (i % 3 === 0) {
console.log('Fizz');
} else if (i % 5 === 0) {
console.log('Buzz');
} else {
console.log(i);
}
}
```
Break and Continue Statements Fill In
In programming, the break statement is used to terminate the loop and exit its current _______________.
In contrast, the continue statement is used to skip the remaining statements inside the loop for the current iteration and move on to the _______________.
Fill in the blanks with the appropriate words.
Generating Complete
Generating complete for this lesson!