?? A short Guide to JavaScript Conditionals and Loops ??

?? A short Guide to JavaScript Conditionals and Loops ??

??? JavaScript, like all programming languages, provides tools to manage the flow of a program. By controlling when and how code executes using conditional statements and loops, developers can build dynamic, interactive web applications. Mastering these tools empowers you to create programs that respond to user input, adapt to data, and perform repetitive tasks efficiently. ??


??? Conditional Statements

Conditional statements allow your code to make decisions by executing different blocks of code depending on whether certain conditions are true or false. This enables your programs to respond dynamically to user inputs, data changes, or other conditions.


1. if Statement

The if statement is the fundamental building block of conditional logic. It allows the program to execute a block of code only if a given condition is true.

Example:

let userStatus = "admin";

if (userStatus === "admin") {
  console.log("Welcome, Admin! You have full access.");
}        

In this example, the if statement checks if userStatus is equal to "admin". If so, the message for the admin will display. If it isn't, the block won't execute, and the user will see no output.


2. if-else Statement

When you need an alternative action if the condition is false, use the if-else statement.

let points = 45;

if (points >= 50) {
  console.log("Congratulations! You passed.");
} else {
  console.log("Try again to improve your score.");
}        

Here, if points are greater than or equal to 50, it displays a congratulatory message. If the condition is false, the alternative message prompts the user to try again.


3. else-if Statement

Sometimes, you have multiple conditions to check. The else-if statement allows you to chain multiple conditions, stopping as soon as one is true.

let temperature = 15;

if (temperature > 30) {
  console.log("It's hot outside.");
} else if (temperature >= 20) {
  console.log("It's warm outside.");
} else if (temperature >= 10) {
  console.log("It's a bit chilly.");
} else {
  console.log("It's cold outside.");
}        

The code checks the temperature and displays the corresponding message. This sequence allows for granular checks with a specific response for each range.


4. switch Statement

The switch statement is ideal when a variable can have many possible values, and you want different outcomes for each value.

Example:

let season = "spring";

switch (season) {
  case "winter":
    console.log("It's winter! Time for hot chocolate.");
    break;
  case "spring":
    console.log("Spring is here! Flowers are blooming.");
    break;
  case "summer":
    console.log("It's summer! Let's hit the beach.");
    break;
  case "fall":
    console.log("Fall has arrived, and leaves are falling.");
    break;
  default:
    console.log("That's not a season.");
}        

The switch statement examines the value of season and displays a message based on each case. The default case handles any value not specifically listed.


?? Loops

Loops allow you to repeat blocks of code until a certain condition is met, making them perfect for tasks like processing elements in arrays, counting down timers, or working with large datasets.


1. for Loop

The for loop is commonly used for repeating a block of code a specific number of times.

Example:

for (let i = 1; i <= 5; i++) {
  console.log(`This is repetition number: ${i}`);
}        

In this example, the loop runs five times. Each repetition logs the current count, providing a flexible way to repeat tasks.

Advanced Example: Loop through an array and find numbers divisible by both 3 and 5.

let numbers = [1, 15, 3, 10, 5, 30, 45];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 3 === 0 && numbers[i] % 5 === 0) {
    console.log(`${numbers[i]} is divisible by both 3 and 5`);
  }
}        


2. while Loop

A while loop continues executing as long as a condition remains true. It’s particularly useful when you don't know how many times the loop will need to run.

Example:

let counter = 0;

while (counter < 3) {
  console.log("Hello, JavaScript!");
  counter++;
}        

The while loop above prints "Hello, JavaScript!" three times, incrementing counter each time until it reaches 3.

Advanced Example: Loop until a user guess matches a target number.

let target = Math.floor(Math.random() * 10) + 1;
let guess;

while (guess !== target) {
  guess = parseInt(prompt("Guess the number (1 to 10): "));

  if (guess === target) {
    console.log("Correct! You've guessed the number.");
  } else {
    console.log("Wrong! Try again.");
  }
}        


3. do-while Loop

The do-while loop is similar to while but guarantees at least one run because the condition is checked after the code block.

Example:

let attempts = 0;
let password;

do {
  password = prompt("Enter your password:");
  attempts++;
} while (password !== "secure123" && attempts < 3);

if (password === "secure123") {
  console.log("Welcome!");
} else {
  console.log("Access denied. Too many attempts.");
}        

This loop prompts the user to enter a password and checks after each attempt, limiting tries to three.


4. forEach Loop

The forEach loop is for arrays, executing a function for each element.

Example:

let colors = ["Red", "Green", "Blue"];

colors.forEach(function (color) {
  console.log(`Color: ${color}`);
});        

This loop iterates over the colors array, logging each color.

Advanced Example: Logging names and positions of employees.

let employees = ["Alice", "Bob", "Charlie"];

employees.forEach((employee, index) => {
  console.log(`${index + 1}. ${employee}`);
});        


?? Combining Conditional Statements and Loops

Combining conditionals and loops is common, enabling complex logic for real-world applications.

Example: Filtering and categorizing numbers in an array.

let mixedNumbers = [8, 12, 5, 6, 7, 20, 21];

for (let i = 0; i < mixedNumbers.length; i++) {
  if (mixedNumbers[i] % 2 === 0) {
    console.log(`${mixedNumbers[i]} is even.`);
  } else if (mixedNumbers[i] % 3 === 0) {
    console.log(`${mixedNumbers[i]} is divisible by 3.`);
  } else {
    console.log(`${mixedNumbers[i]} is neither even nor divisible by 3.`);
  }
}        

?? Pro Tips for Conditions and Loops

  1. Keep Conditions Simple: Use helper functions for complex conditions to make code readable.
  2. Use Break and Continue Carefully: In loops, break exits the loop, and continue skips the current iteration. Use them sparingly to avoid hard-to-read code.
  3. Consider Array Methods for Complex Iteration: Array methods like .filter(), .map(), and .reduce() are often more concise than traditional loops.
  4. Avoid Nested Loops: When possible, avoid loops within loops, which can slow down performance, especially for large datasets.

Understanding how and when to use these tools brings you closer to becoming an adept JavaScript developer!


If you haven’t purchased Expressive Emojis yet, what are you waiting for? Get your copy now and dive into Simplex Noise, dat.GUI, and Three.js, along with beautiful emoji animations that you can control in terms of speed and size, are all packed into one comprehensive book.

Get your copy now ?? https://books2read.com/expressive-emojis


要查看或添加评论,请登录

Stelvin Saji的更多文章

社区洞察

其他会员也浏览了