Day 7: JavaScript Operators, Conditionals, Loops
Overview
Today, we will continue exploring JavaScript by learning about operators, conditionals, and loops. These are fundamental concepts that allow you to perform operations, make decisions, and execute repetitive tasks in your code.
JavaScript Operators
Operators are used to perform operations on variables and values. JavaScript includes several types of operators:
- Arithmetic Operators: Used to perform arithmetic operations like addition, subtraction, multiplication, etc.
- Assignment Operators: Used to assign values to variables.
- Comparison Operators: Used to compare two values.
- Logical Operators: Used to combine two or more conditions.
Examples:
// Arithmetic Operators
let a = 5;
let b = 2;
let sum = a + b; // 7
let diff = a - b; // 3
// Assignment Operators
let x = 10;
x += 5; // 15
// Comparison Operators
let isEqual = (a == b); // false
// Logical Operators
let isTrue = (a > b && x > a); // true
Conditionals
Conditional statements are used to perform different actions based on different conditions. JavaScript supports the following conditional statements:
- if: Executes a block of code if a specified condition is true.
- else: Executes a block of code if the same condition is false.
- else if: Specifies a new condition to test if the first condition is false.
- switch: Specifies many alternative blocks of code to be executed.
Examples:
// if, else if, else
let time = 20;
if (time < 10) {
console.log("Good morning");
} else if (time < 20) {
console.log("Good day");
} else {
console.log("Good evening");
}
// switch
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Another day");
}
Loops
Loops are used to execute a block of code a number of times. JavaScript supports different kinds of loops:
- for: Loops through a block of code a number of times.
- while: Loops through a block of code while a specified condition is true.
- do...while: Also loops through a block of code while a specified condition is true, but will always execute the block at least once.
Examples:
// for loop
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
// while loop
let j = 0;
while (j < 5) {
console.log("The number is " + j);
j++;
}
// do...while loop
let k = 0;
do {
console.log("The number is " + k);
k++;
} while (k < 5);
Practice Exercise
Try creating a simple JavaScript script that does the following:
- Uses a loop to print numbers from 1 to 10.
- Uses a conditional statement to print "Even" or "Odd" for each number.
// Your code here
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i + " is Even");
} else {
console.log(i + " is Odd");
}
}
Summary
In today's lesson, we covered JavaScript operators, conditionals, and loops. You learned how to perform operations, make decisions, and execute repetitive tasks in your JavaScript code.