Decision and Loops
Learn Decision and Loops step by step with clear examples and exercises.
Why This Matters
In this full guide on JavaScript Decision and Loops, we will delve deep into the essential concepts of decision making (if statements) and looping structures (for loops and while loops). These fundamental constructs are crucial for any JavaScript programmer as they allow you to control the flow of your code, creating dynamic programs that can handle various input scenarios and perform repetitive tasks efficiently. Whether you're building a simple calculator or a complex web application, mastering decision and loops in JavaScript will be an indispensable skill.
Prerequisites
Before diving into the core concepts of decision making and looping structures, it is essential to have a basic understanding of the following:
- Variables and data types in JavaScript
- Basic JavaScript syntax (e.g., functions, operators)
- DOM manipulation (selecting and modifying HTML elements)
Variables and Data Types
In JavaScript, variables can store different data types such as numbers, strings, booleans, arrays, objects, and null. Understanding these data types is essential for working with decision making and looping structures effectively.
let num = 10; // number
let name = "John"; // string
let isStudent = true; // boolean
let myArray = [1, 2, 3]; // array
let myObject = { name: "Jane", age: 25 }; // object
let nullValue = null; // null
Basic JavaScript Syntax
Familiarize yourself with basic JavaScript syntax such as functions, operators, and control structures like if statements. This will help you write more efficient and effective code when working with decision making and looping structures.
// Function declaration
function greet(name) {
console.log("Hello, " + name + "!");
}
// Function expression
let greetFunction = function (name) {
console.log("Hello, " + name + "!");
};
// Operators
let x = 5;
let y = 10;
console.log(x + y); // addition
console.log(x - y); // subtraction
console.log(x * y); // multiplication
console.log(x / y); // division
console.log(x % y); // modulus (remainder)
console.log(x > y); // greater than
console.log(x < y); // less than
DOM Manipulation
Knowledge of DOM manipulation is essential for creating dynamic web applications that interact with the user interface. You can use JavaScript to select and modify HTML elements using methods such as document.getElementById(), document.querySelector(), and document.querySelectorAll().
// Select an element by ID
let myElement = document.getElementById("myId");
// Modify the text content of an element
myElement.textContent = "New Text";
Core Concept
If Statements
The if statement in JavaScript is used to test a condition and execute code based on the result. Here's an example:
let num = 10;
if (num > 5) {
console.log("The number is greater than 5.");
}
In this example, we have a variable num with a value of 10. The if statement checks whether the condition (num > 5) is true, and if so, it logs the message "The number is greater than 5." to the console.
You can also use else statements to specify code that should be executed when the condition is false:
let num = 5;
if (num > 10) {
console.log("The number is greater than 10.");
} else {
console.log("The number is less than or equal to 10.");
}
For Loops
For loops are used for iterating over a specific range of values. Here's an example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example, we have a for loop that initializes a variable i to 0 and continues as long as the condition (i < 5) is true. Inside the loop, we log the current value of i to the console on each iteration.
While Loops
While loops continue executing as long as a specified condition remains true. Here's an example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
In this example, we have a while loop that initializes a variable i to 0 and continues as long as the condition (i < 5) is true. Inside the loop, we log the current value of i to the console on each iteration and increment i by 1 before checking the condition again.
Worked Example
Let's create a simple JavaScript program that calculates the sum of all even numbers between 1 and 100 using both for loops and while loops:
let total = 0;
// Using a for loop
for (let i = 2; i <= 100; i += 2) {
total += i;
}
console.log("Sum using for loop:", total);
// Using a while loop
let num = 2;
while (num <= 100) {
total += num;
num += 2;
}
console.log("Sum using while loop:", total);
In this example, we initialize a variable total to 0 and use both for loops and while loops to calculate the sum of all even numbers between 1 and 100. The output will be:
Sum using for loop: 2500
Sum using while loop: 2500
Common Mistakes
- Forgetting to initialize a counter variable in for loops
- Using the wrong comparison operator (e.g.,
=instead of==) - Not updating the counter variable inside the loop body
- Misusing the else keyword with if statements (e.g., forgetting to include an if statement before the else)
Common Mistakes - For Loops
- Forgetting to initialize a counter variable:
for (let i; i < 5; i++) { // missing initialization
console.log(i);
}
- Using the wrong comparison operator:
for (let i = 0; i = 5; i++) { // using assignment instead of comparison
console.log(i);
}
Common Mistakes - While Loops
- Not updating the counter variable inside the loop body:
let i = 0;
while (i < 5) {
console.log(i);
} // missing increment statement
Practice Questions
- Write a JavaScript function that checks whether a given number is even or odd.
- Create a JavaScript program that calculates the sum of all numbers between 1 and 100 using only while loops.
- Write a JavaScript code snippet that finds the largest prime number less than or equal to 50.
FAQ
How do I create an infinite loop in JavaScript?
To create an infinite loop in JavaScript, you can use either a while loop with no condition or a for loop with no end value:
// Infinite while loop
let i = 0;
while (true) {
console.log(i);
i++;
}
// Infinite for loop
for (let i = 0;;) {
console.log(i);
i++;
}
What's the difference between == and === in JavaScript?
In JavaScript, == performs type coercion when comparing values, while === does not. This means that == will convert data types (e.g., converting a string to a number), whereas === will only compare equal values of the same data type:
console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (different data types)