The Front-End
JavaScript
Conditionals, Loops, and Functions

Conditional Statements, Loops, and Functions in JavaScript

  1. Conditional Statements
  2. Loops
  3. Functions and Their Role

Conditional Statements

Conditional statements allow you to make decisions in your code based on certain conditions. The most common types of conditional statements in JavaScript are if, else, and switch.

Example (if-else):

let temperature = 25;
 
if (temperature > 30) {
  console.log("It's a hot day!");
} else if (temperature >= 20 && temperature <= 30) {
  console.log("The weather is pleasant.");
} else {
  console.log("It's a cold day.");
}

Example (switch):

let dayOfWeek = 3;
let dayName;
 
switch (dayOfWeek) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  // Add more cases as needed
  default:
    dayName = "Unknown";
}
console.log(`Today is ${dayName}.`);

Loops

Loops allow you to execute a block of code repeatedly. Common loop types in JavaScript are for and while.

Example (for loop):

for (let i = 1; i <= 5; i++) {
  console.log(`Iteration ${i}`);
}

Example (while loop):

let countdown = 5;
 
while (countdown > 0) {
  console.log(`Countdown: ${countdown}`);
  countdown--;
}

Functions and Their Role

Functions are reusable blocks of code that perform a specific task. They help in organizing and modularizing code, making it more readable and maintainable. Functions in JavaScript can take parameters and return values.

Example:

// Function declaration
function greet(name) {
  console.log(`Hello, ${name}!`);
}
 
// Function call
greet("Alice");

Example (Function with Return Value):

function add(a, b) {
  return a + b;
}
 
let result = add(3, 7);
console.log(`The sum is: ${result}`);

Example (Arrow Function):

// Arrow function
const multiply = (x, y) => x * y;
 
let product = multiply(4, 5);
console.log(`The product is: ${product}`);

These examples cover the basics of conditional statements (if, else, switch), loops (for, while), and functions in JavaScript. As you advance in your JavaScript journey, you'll encounter more complex scenarios where these concepts play a crucial role in writing efficient and structured code.