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:
1// Using an if statement to check if a number is positive
2const number = 5;
3
4if (number > 0) {
5 console.log('The number is positive');
6}
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.
xxxxxxxxxx
// 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');
}
Let's test your knowledge. Is this statement true or false?
The if
statement is used to make decisions based on certain conditions.
Press true if you believe the statement is correct, or false otherwise.
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:
1if (condition) {
2 // code to execute if condition is true
3}
Let's look at an example to understand how the if
statement works:
1const age = 25;
2
3if (age >= 18) {
4 console.log('You are eligible to vote!');
5}
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:
1const num = 10;
2
3if (num % 2 === 0) {
4 console.log('The number is even');
5} else {
6 console.log('The number is odd');
7}
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:
1const grade = 85;
2
3if (grade >= 90) {
4 console.log('A');
5} else if (grade >= 80) {
6 console.log('B');
7} else if (grade >= 70) {
8 console.log('C');
9} else if (grade >= 60) {
10 console.log('D');
11} else {
12 console.log('F');
13}
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.
Are you sure you're getting this? Is this statement true or false?
The if
statement is used to selectively execute a code block if a condition is true.
Press true if you believe the statement is correct, or false otherwise.
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:
1if (condition) {
2 // code to execute if condition is true
3} else {
4 // code to execute if condition is false
5}
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:
1const age = 25;
2
3if (age < 18) {
4 console.log('Sorry, you are not eligible to vote.');
5} else {
6 console.log('You are eligible to vote!');
7}
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:
1const num = 10;
2
3if (num % 2 === 0) {
4 console.log('The number is even');
5} else {
6 console.log('The number is odd');
7}
xxxxxxxxxx
const age = 25;
if (age < 18) {
console.log('Sorry, you are not eligible to vote.');
} else {
console.log('You are eligible to vote!');
}
Let's test your knowledge. Fill in the missing part by typing it 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:
1if (condition) {
2 // code to execute if condition is true
3} else {
4 // code to execute if condition is false
5}
In the context of conditional statements, the _____________
block is executed if the condition is false.
Write the missing line below.
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:
1const age = 20;
2const hasLicense = true;
3
4if (age >= 18) {
5 if (hasLicense) {
6 console.log('You are eligible to drive.');
7 } else {
8 console.log('You are eligible to apply for a license.');
9 }
10} else {
11 console.log('You are not eligible to drive or apply for a license.');
12}
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!
xxxxxxxxxx
// 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.');
}
Build your intuition. Is this statement true or false?
Nested if-else statements allow you to test for more specific conditions within the scope of a broader condition.
Press true if you believe the statement is correct, or false otherwise.
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:
1const day = 'Monday';
2
3switch (day) {
4 case 'Monday':
5 console.log('It is the beginning of the week.');
6 break;
7 case 'Tuesday':
8 console.log('It is the second day of the week.');
9 break;
10 case 'Wednesday':
11 console.log('It is the middle of the week.');
12 break;
13 case 'Thursday':
14 case 'Friday':
15 console.log('It is almost the weekend.');
16 break;
17 default:
18 console.log('It is the weekend.');
19}
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!
xxxxxxxxxx
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.');
}
Let's test your knowledge. Click the correct answer from the options.
Which statement is true about switch statements in JavaScript?
Click the option that best answers the question.
- They can only be used with string values
- They can handle multiple conditions using the switch keyword
- They always require a default case
- They are an alternative to if-else statements
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.
1const numbers = [1, 2, 3, 4, 5];
2
3for (let i = 0; i < numbers.length; i++) {
4 console.log(numbers[i]);
5}
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.
xxxxxxxxxx
// Let's log the numbers from 1 to 10 using a for loop
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Are you sure you're getting this? Fill in the missing part by typing it in.
A loop is used to ___ a block of code multiple times until a certain condition is met.
Write the missing line below.
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:
1// Iterating over an array using a for loop
2const colors = ['red', 'green', 'blue'];
3
4for (let i = 0; i < colors.length; i++) {
5 console.log(colors[i]);
6}
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.
xxxxxxxxxx
// 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]);
}
Try this exercise. Fill in the missing part by typing it in.
A for loop is used to iterate over a collection of items. It consists of three parts: initialization, condition, and _.
Write the missing line below.
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:
1while (condition) {
2 // code to be executed
3}
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:
1let num = 1;
2
3while (num <= 10) {
4 console.log(num);
5 num++;
6}
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.
xxxxxxxxxx
// Example of a while loop
let count = 1;
while (count <= 5) {
console.log(`Count: ${count}`);
count++;
}
Build your intuition. Is this statement true or false?
The condition of a while loop is evaluated before each iteration.
Press true if you believe the statement is correct, or false otherwise.
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:
1do {
2 // code to be executed
3} while (condition);
Here's an example that demonstrates the usage of a do-while loop:
1let x = 1;
2
3do {
4 console.log(x);
5 x++;
6} 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.
xxxxxxxxxx
// JavaScript code example
let x = 1;
do {
console.log(x);
x++;
} while (x <= 5);
Let's test your knowledge. Click the correct answer from the options.
Which of the following statements about do-while loops in JavaScript is true?
Click the option that best answers the question.
- The code inside a do-while loop is only executed if the condition is true
- A do-while loop is guaranteed to execute the code block at least once
- The condition of a do-while loop is checked before executing the code block
- A do-while loop is a version of the while loop in JavaScript
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:
1for (let i = 1; i <= 10; i++) {
2 if (i === 5) {
3 break;
4 }
5 console.log(i);
6}
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:
1for (let i = 1; i <= 10; i++) {
2 if (i % 2 === 0) {
3 continue;
4 }
5 console.log(i);
6}
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.
xxxxxxxxxx
// 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);
}
}
Try this exercise. Fill in the missing part by typing it 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.
Write the missing line below.
Generating complete for this lesson!