Day 2: Mastering JavaScript Logic: If Statements, Loops, and Functions
Conditional Statements
JavaScript provides conditional statements to control the flow of a program based on certain conditions.
if
, else if
, else
let hour = new Date().getHours();
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
Loops
Loops allow you to repeatedly execute a block of code. JavaScript supports for
, while
, and do-while
loops.
for
Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
while
Loop
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
Functions
Functions in JavaScript are reusable blocks of code that perform a specific task. They enhance code organization and maintainability.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("John"));
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(5, 3));
Explain the purpose of conditional statements in JavaScript.
Answer: Conditional statements allow us to execute different code blocks based on specified conditions, providing control over the flow of the program.
How does the for
loop work in JavaScript?
Answer: The for
loop has three parts: initialization, condition, and increment/decrement. It repeatedly executes a block of code until the condition becomes false.
What is the difference between a function declaration and a function expression?
Answer: Function declarations are hoisted, meaning they are processed before the code execution starts. Function expressions are not hoisted and must be defined before use.
Why might you choose to use a while
loop over a for
loop or vice versa?
Answer: for
loops are ideal when the number of iterations is known, while while
loops are suitable when the number of iterations is determined by a condition.
“Cracking the Code: Mastering JavaScript Logic with If, Loops, and Functions”
“JavaScript Logic Mastery: Exploring If Statements, Loops, and Functions”
“Unleashing JavaScript Logic: Ifs, Loops, and Functions Demystified”
“Diving Deep into JavaScript Logic: Ifs, Loops, and the Magic of Functions”
“Becoming a JavaScript Logic Pro: If Statements, Loops, and Functions Explored”