Conditions & loops in React JS
Course: React JS Training
Topic: Conditions & loops
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Why conditions and loops matter
Every useful program has to make decisions and repeat work. A login form decides whether a password is correct. A shopping cart decides whether an item is in stock. A report page prints one row per student, even when there are five hundred students. Without a way to say "if this is true, do that" and a way to say "do this again until we run out of items", you would have to write separate code for every possible situation, which is impossible in practice.
Conditions and loops are the two tools that solve this. In JavaScript they are built from a small set of keywords: if, else, switch, for, while, do...while, break and continue. These ideas are not just for plain JavaScript. When you later write React components, you will constantly decide what to render based on state, and you will turn arrays of data into lists of elements using loop-like logic. A weak understanding of conditions and loops shows up later as confusion in React code, so this sub-module deserves slow, careful study.
By the end of this page you will be able to read and write code that answers questions ("is the user logged in?") and repeats tasks ("print every mark in the list"), which together cover a very large share of everyday programming work.
2. Conditions and loops in simple words
What is a condition?
A condition is a question with a yes or no answer. In JavaScript, that answer is a boolean value: true or false. A conditional statement runs one block of code only when the answer is true, and optionally a different block when the answer is false.
Think of a railway crossing gate. If a train is coming, the gate closes; otherwise, traffic passes. The program checks a fact, then picks one path.
What is a loop?
A loop repeats a block of code several times. You give the loop three pieces of information: where to start, when to stop, and what changes on each pass. The loop then runs the same block again and again until the stopping rule says "enough".
Think of a teacher marking papers one by one. The teacher does not learn a new marking method for each paper; the same method is repeated, and the pile shrinks each time. When the pile is empty, the repetition stops.
How they work together
Real code almost always combines both. "For every student in the list (a loop), check whether the student passed (a condition), and print the result accordingly." The loop walks through the data; the condition decides what happens to each item.
3. Key terms
| Term | Meaning |
| Boolean | A value that is either true or false. Every condition finally becomes a boolean. |
| Expression | Any piece of code that produces a value, for example age >= 18 or marks > 35. |
| Condition | An expression placed inside if, while and similar keywords, which JavaScript converts to true or false. |
| Block | A group of statements wrapped in curly braces { }. A block runs as one unit. |
| Iteration | One single pass through a loop. If a loop runs five times, it has completed five iterations. |
| Loop counter | The variable that counts how far the loop has gone, usually named i, j or index. |
| Infinite loop | A loop whose stopping condition never becomes false, so it runs forever and can freeze the browser tab. |
| Nesting | Placing one condition or loop inside another, for example a loop that contains an if. |
4. The if statement: syntax and how it is evaluated
Basic syntax
if (condition) {
// this block runs only when condition is true
}
The word if is followed by a condition inside round brackets, then a block inside curly braces. JavaScript first evaluates the condition. If the result is true (or a value that behaves like true), the block runs. If not, the block is skipped completely and the program continues after the closing brace.
Step-by-step evaluation
Take this small example and follow it line by line.
let temperature = 42;
if (temperature > 40) {
console.log("Heat warning issued");
}
console.log("Program finished");
- JavaScript creates the variable
temperature with the value 42.
- It reaches the
if and evaluates the condition temperature > 40. Since 42 is greater than 40, the condition produces true.
- Because the answer is
true, the block runs and prints Heat warning issued.
- The program leaves the block and prints
Program finished.
If temperature had been 30, step 2 would have produced false, step 3 would have been skipped, and only Program finished would appear. Nothing breaks and no error occurs; the block is simply ignored.
Common syntax mistakes
- Writing a semicolon right after
if (condition);. This ends the statement early, and the block below runs every time, unconnected to the condition.
- Using
= (assignment) instead of == or === (comparison) inside the condition. if (x = 5) assigns 5 to x instead of comparing.
- Forgetting curly braces when the block has several lines. Without braces, only the very next statement belongs to the
if, which causes confusing bugs. Always use braces.
5. else and else if: building multi-branch logic
Adding else
else gives your program a second path for the "no" answer.
let password = "abc123";
if (password === "abc123") {
console.log("Welcome back!");
} else {
console.log("Incorrect password");
}
Exactly one of the two blocks runs, never both and never neither. This either-or structure is called a binary branch.
Adding else if for more paths
When there are more than two possible situations, chain conditions with else if. JavaScript checks them from top to bottom and runs the first block whose condition is true, skipping all the rest.
let marks = 72;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else if (marks >= 60) {
console.log("Grade: C");
} else if (marks >= 35) {
console.log("Grade: D");
} else {
console.log("Grade: F (fail)");
}
// Output: Grade: C
With marks = 72, the first condition (72 >= 90) is false, the second (72 >= 75) is false, the third (72 >= 60) is true, so Grade: C prints and the remaining checks never run. The final else acts as a safety net that catches every value the earlier checks missed.
Rules for chaining
- Order matters. If the first check were
marks >= 35, a student with 95 would be graded D and the chain would stop there. Put the most specific or highest condition first.
- Only one block in the whole chain runs.
- The trailing
else is optional, but it is good practice because it handles unexpected values explicitly.
6. Comparison and logical operators in conditions
Comparison operators
Comparison operators compare two values and return a boolean.
| Operator | Meaning | Example | Result |
=== | Strictly equal (value and type) | 5 === 5 | true |
!== | Strictly not equal | 5 !== "5" | true |
== | Loosely equal (converts types) | 5 == "5" | true |
!= | Loosely not equal | 5 != "6" | true |
> | Greater than | 10 > 3 | true |
< | Less than | 2 < 1 | false |
>= | Greater than or equal | 7 >= 7 | true |
<= | Less than or equal | 4 <= 3 | false |
Prefer === and !== in real code. The loose versions == and != convert types before comparing, which produces surprising results such as 0 == "" being true. Strict comparison keeps types honest and avoids a whole family of bugs.
Logical operators
Logical operators combine several boolean checks into one condition.
| Operator | Name | True when... | Example |
&& | AND | both sides are true | age >= 18 && hasID |
|| | OR | at least one side is true | isWeekend || isHoliday |
! | NOT | the value is false (it flips it) | !isBanned |
let age = 20;
let hasID = true;
if (age >= 18 && hasID) {
console.log("Entry allowed");
}
let isMember = false;
let hasCoupon = true;
if (isMember || hasCoupon) {
console.log("Discount applied");
}
let isBanned = false;
if (!isBanned) {
console.log("Account active");
}
All three messages print here. Notice how && demands both facts, || accepts either one, and ! reverses a single fact.
Short-circuit behaviour
JavaScript stops evaluating a logical expression as soon as the answer is certain. In a && b, if a is false, b is never checked because the result is already false. In a || b, if a is true, b is never checked. This is called short-circuiting, and it is often used to guard against errors:
if (user !== undefined && user.age >= 18) {
console.log("Adult user");
}
The second check only runs when user exists, so the code never tries to read a property of something that is not there.
7. Truthy and falsy values
A condition does not have to be a comparison. JavaScript can convert any value into a boolean. Values that behave like true are called truthy; values that behave like false are called falsy.
The six falsy values
false
0 (and -0)
"" (an empty string)
null
undefined
NaN (not a number)
Everything else is truthy, including "0", "false" (a non-empty string), [] (an empty array) and {} (an empty object).
Why this is useful
let username = "";
if (username) {
console.log("Hello, " + username);
} else {
console.log("Please enter a username");
}
// Output: Please enter a username
An empty string is falsy, so the else branch runs. This pattern is everywhere in real code: check a value directly instead of writing long comparisons. Similarly, if (cartItems) is a quick way to test whether a list or object actually exists before working with it.
A trap to remember
Because an empty array is truthy, if (items) is true even when the array has zero elements. To test emptiness, check the length: if (items.length > 0). Misreading this trap is a very common beginner mistake.
8. The switch statement
switch is an alternative to a long if / else if chain when one value is being compared against several fixed options.
Syntax
let dayNumber = 3;
switch (dayNumber) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day number");
}
// Output: Wednesday
How it works, step by step
- JavaScript evaluates the expression in
switch ( ) once, here dayNumber which is 3.
- It compares that value against each
case label from top to bottom using strict comparison (===).
- When it finds a match, it runs the code from that label downwards.
break stops the switch and jumps out. Without break, execution "falls through" into the next case, which is usually unwanted.
default runs when no case matched, like a final else.
When to choose switch over if
| Situation | Better choice |
| Comparing one variable against several exact values (menu choice, status code, day of week) | switch, because it reads cleanly |
Checking ranges such as marks >= 75 | if / else if, because switch matches exact values, not ranges |
Combining several different facts with && and || | if, because switch cannot combine conditions |
One practical trick: several cases can share one block by stacking labels, which is a clean way to group values.
let month = 5;
switch (month) {
case 12:
case 1:
case 2:
console.log("Winter");
break;
case 3:
case 4:
case 5:
console.log("Spring");
break;
default:
console.log("Other season");
}
// Output: Spring
9. The ternary operator
The ternary operator (also called the conditional operator) is a one-line version of if / else that produces a value. It is called "ternary" because it takes three parts: a condition, a result for true, and a result for false.
Syntax
condition ? valueIfTrue : valueIfFalse
Example
let age = 17;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // minor
The same logic written with if / else would need four lines. The ternary version is popular when you want to pick between two values, especially when assigning to a variable or building a string.
let marks = 82;
let result = marks >= 35 ? "Pass" : "Fail";
console.log("Result: " + result); // Result: Pass
Guidelines
- Use the ternary for simple, short choices between two values.
- Do not nest ternaries inside ternaries.
a ? b ? x : y : z is legal but very hard to read; use if / else if instead.
- Do not use a ternary where you need to run several statements; blocks belong to
if.
10. The for loop
The for loop is the most common loop in JavaScript. It packs the three ingredients of repetition into one line: a starting counter, a condition that decides whether to continue, and a step that updates the counter.
Syntax
for (let i = 1; i <= 5; i++) {
console.log("Iteration number " + i);
}
Inside the brackets, separated by semicolons:
- Initialisation:
let i = 1 runs once, before anything else. It creates the counter.
- Condition:
i <= 5 is checked before every iteration. The body runs only while it is true.
- Update:
i++ runs after every iteration, moving the counter towards the stopping point.
Execution order, step by step
- Initialisation:
i becomes 1.
- Condition check:
1 <= 5 is true, so the body runs and prints Iteration number 1.
- Update:
i becomes 2.
- Condition check:
2 <= 5 is true, body runs again.
- This cycle repeats. When
i becomes 6, the condition 6 <= 5 is false, the loop ends, and the program continues after the loop.
Output:
Iteration number 1
Iteration number 2
Iteration number 3
Iteration number 4
Iteration number 5
Looping through an array by index
The most frequent real-world use is visiting every element of an array. Array indexes start at 0, so the counter usually starts at 0 and continues while i < array.length.
let fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(i + ": " + fruits[i]);
}
// Output:
// 0: apple
// 1: banana
// 2: mango
Note the strict "<" rather than "<=". If you wrote i <= fruits.length, the last iteration would try to read fruits[3], which does not exist, and print undefined.
Counting down and stepping
for (let i = 10; i > 0; i--) {
console.log(i);
}
console.log("Lift off!");
for (let i = 0; i <= 20; i += 5) {
console.log(i); // prints 0, 5, 10, 15, 20
}
The update expression is flexible: i-- counts down, i += 5 jumps in steps of five. The condition and update simply have to agree, so the counter moves towards a state where the condition becomes false.
11. while and do...while loops
The while loop
A while loop repeats as long as its condition stays true. Unlike for, it does not keep the counter inside its own header; you manage the variable yourself.
Syntax
let count = 1;
while (count <= 3) {
console.log("Count is " + count);
count++;
}
// Output:
// Count is 1
// Count is 2
// Count is 3
Execution order: check the condition, run the body if true, return to the check. The update (count++) is your responsibility. Forgetting it is the classic cause of an infinite loop, because the condition never changes.
When while fits better than for
Use while when you do not know in advance how many repetitions are needed. For example, keep dividing a number until it becomes smaller than one:
let value = 100;
let steps = 0;
while (value >= 1) {
value = value / 2;
steps++;
}
console.log(steps); // 7
You cannot predict the number of iterations just by looking; it depends on the starting value. That uncertainty is the signal to use while.
The do...while loop
do...while runs the body first and checks the condition afterwards. This guarantees at least one iteration, even if the condition is false from the start.
let number = 10;
do {
console.log("Number is " + number);
number++;
} while (number < 3);
// Output: Number is 10
Here the condition number < 3 is false immediately, yet the body still ran once. Compare this with a plain while, which would have skipped the body entirely.
Comparing the three loops
| Loop | Condition checked | Minimum iterations | Typical use |
for | Before each iteration | Zero | Known number of repeats, walking through arrays by index |
while | Before each iteration | Zero | Unknown number of repeats driven by a changing value |
do...while | After each iteration | One | Work that must happen at least once, such as showing a prompt once before re-checking |
12. break and continue
Two keywords give you fine control inside any loop.
break: leave the loop now
break stops the loop immediately and moves the program to the first line after the loop.
let numbers = [4, 8, 15, 16, 23, 42];
let found = -1;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 15) {
found = i;
break;
}
}
console.log("15 found at index " + found); // 15 found at index 2
Once the target is found, checking the remaining elements is wasted work, so break exits early. This "search and stop" pattern is extremely common.
continue: skip this iteration only
continue abandons the current pass and jumps straight to the next one. The loop itself keeps running.
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) {
continue; // skip odd numbers
}
console.log(i);
}
// Output: 2, 4, 6, 8, 10
For every odd number, the continue fires and the console.log below it is skipped for that pass only. Even numbers pass through normally.
break in switch versus break in loops
break has two jobs: inside switch it prevents fall-through between cases, and inside loops it ends the loop. continue only works inside loops.
A caution about infinite loops
If the loop condition never becomes false, the loop never ends. In the browser this freezes the tab, because the page's single thread is stuck in the loop. Always confirm that the variable in your condition is updated inside the loop, and that the update moves it towards the exit.
13. Worked realistic examples
Example 1: a grading report combining a loop and conditions
This example walks through an array of marks, applies the grading rules from earlier, and counts how many students passed.
let marks = [88, 45, 72, 30, 95, 61];
let passed = 0;
for (let i = 0; i < marks.length; i++) {
let mark = marks[i];
if (mark >= 90) {
console.log("Student " + (i + 1) + ": Grade A");
} else if (mark >= 75) {
console.log("Student " + (i + 1) + ": Grade B");
} else if (mark >= 60) {
console.log("Student " + (i + 1) + ": Grade C");
} else if (mark >= 35) {
console.log("Student " + (i + 1) + ": Grade D");
} else {
console.log("Student " + (i + 1) + ": Grade F");
}
if (mark >= 35) {
passed++;
}
}
console.log(passed + " out of " + marks.length + " students passed");
Output:
Student 1: Grade A
Student 2: Grade D
Student 3: Grade C
Student 4: Grade F
Student 5: Grade A
Student 6: Grade C
5 out of 6 students passed
Notice the division of labour: the loop visits each mark, the first chain of conditions picks a grade, and a second independent condition updates the counter. Conditions inside a loop do not have to be a single chain; you can use as many separate checks as the task needs.
Example 2: a simple login attempt limit with while
let storedPassword = "open2026";
let entered = "";
let attempts = 0;
let maxAttempts = 3;
let loggedIn = false;
while (attempts < maxAttempts && !loggedIn) {
// imagine this line reads input from the user
entered = attempts === 0 ? "wrong" : "open2026";
attempts++;
if (entered === storedPassword) {
loggedIn = true;
console.log("Login successful");
} else {
console.log("Wrong password, attempt " + attempts + " of " + maxAttempts);
}
}
if (!loggedIn) {
console.log("Account locked");
}
Output:
Wrong password, attempt 1 of 3
Login successful
The loop condition combines two facts with &&: attempts must remain below the limit, and the user must not already be logged in. The ! operator turns the boolean loggedIn into the question "not yet logged in?". When either fact fails, the loop stops, and the final if reports the outcome. This mix of a while loop, logical operators and a boolean flag is a realistic shape for many small programs you will write before moving on to functions and, later, React components.
14. Advanced and real-world usage
Nested loops
A loop can sit inside another loop. The inner loop completes all of its iterations for every single iteration of the outer loop. Nested loops are the natural tool for grids, tables and combinations.
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 3; col++) {
line = line + row + "-" + col + " ";
}
console.log("Row " + row + ": " + line);
}
Output:
Row 1: 1-1 1-2 1-3
Row 2: 2-1 2-2 2-3
Row 3: 3-1 3-2 3-3
The outer loop runs 3 times, and for each pass the inner loop also runs 3 times, giving 9 total inner iterations. Keep nesting shallow: two or three levels are readable, deeper nesting usually means the logic should be split into functions (covered in the next sub-module).
Comparing two lists item by item
A common real task is matching items from two arrays, for example marking which students were present.
let allStudents = ["Asha", "Bilal", "Chitra", "Dev"];
let presentToday = ["Bilal", "Dev"];
for (let i = 0; i < allStudents.length; i++) {
let isPresent = false;
for (let j = 0; j < presentToday.length; j++) {
if (allStudents[i] === presentToday[j]) {
isPresent = true;
break;
}
}
if (isPresent) {
console.log(allStudents[i] + " - present");
} else {
console.log(allStudents[i] + " - absent");
}
}
Output:
Asha - absent
Bilal - present
Chitra - absent
Dev - present
This example combines everything from part 1: an outer loop over the main list, an inner loop used as a search, break to stop searching once a match is found, a boolean flag, and a final condition to print the result.
Building strings and HTML-like output in a loop
Loops are often used to assemble a larger piece of text from many small pieces, which is exactly the mental model you will later use in React when rendering a list of items.
let cartItems = ["Keyboard", "Mouse", "Monitor"];
let total = 2500 + 800 + 12000;
let summary = "Your cart (" + cartItems.length + " items):\n";
for (let i = 0; i < cartItems.length; i++) {
summary = summary + (i + 1) + ". " + cartItems[i] + "\n";
}
summary = summary + "Total: Rs. " + total;
console.log(summary);
Output:
Your cart (3 items):
1. Keyboard
2. Mouse
3. Monitor
Total: Rs. 15300
Validation loops: repeat until input is acceptable
Conditions and loops together power input validation. The program keeps asking until the answer passes a rule.
let pin = "";
let tries = 0;
while (pin.length !== 4 || isNaN(Number(pin))) {
tries++;
// imagine this reads a new attempt from the user each time
pin = tries === 1 ? "12a" : "9042";
}
console.log("PIN accepted after " + tries + " attempt(s)");
Output:
PIN accepted after 2 attempt(s)
The condition expresses the rule "keep going while the pin is not exactly four characters or is not a number". Note the use of ||: either failure is enough to reject the input.
15. Common mistakes and the correct way
Off-by-one errors in loops
Mistake: using <= with array.length, which reads one index past the end.
let colours = ["red", "green", "blue"];
for (let i = 0; i <= colours.length; i++) {
console.log(colours[i]); // last line prints undefined
}
Correct way: use < when starting at index 0.
for (let i = 0; i < colours.length; i++) {
console.log(colours[i]); // red, green, blue
}
Forgetting the update in a while loop
Mistake: the counter never changes, so the condition stays true forever.
let i = 0;
while (i < 5) {
console.log(i); // i is never increased: infinite loop
}
Correct way: update the counter inside the body.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Using = instead of === in a condition
Mistake: assignment inside a condition, which silently changes the variable.
let score = 0;
if (score = 100) { // assigns 100, then treats it as truthy
console.log("Perfect score"); // always runs
}
Correct way: compare with strict equality.
if (score === 100) {
console.log("Perfect score"); // runs only when score really is 100
}
Missing break in a switch
Mistake: execution falls through into the next case.
let role = "editor";
switch (role) {
case "editor":
console.log("Can edit articles");
// no break: falls into the next case
case "viewer":
console.log("Can only view");
break;
}
Output shows both lines even though the role is only "editor". Correct way: end every case with break (unless fall-through is deliberate, as in the grouped season example).
Testing an array for emptiness incorrectly
Mistake: an empty array is truthy, so this check passes even with no items.
let items = [];
if (items) {
console.log("You have items"); // prints even though the list is empty
}
Correct way: check the length explicitly.
if (items.length > 0) {
console.log("You have items");
} else {
console.log("Your list is empty");
}
Comparing with the wrong operator for types
Mistake: loose equality hides type differences.
console.log(0 == ""); // true, surprising
console.log("5" == 5); // true, risky
Correct way: strict equality compares value and type.
console.log(0 === ""); // false
console.log("5" === 5); // false
Declaring the loop counter in the wrong scope
Mistake: reusing a counter variable declared outside the loop, which can clash with other code.
let i = 100;
for (let i = 0; i < 3; i++) {
// this i is a separate, loop-only variable
}
console.log(i); // 100, the outer i is untouched
Correct practice: always declare the counter with let inside the for header so each loop owns its own counter. Relying on a shared outer counter is a frequent source of bugs in larger programs.
16. Best practices
- Always use curly braces, even for one-line bodies. It prevents the classic bug where a later-added second line silently sits outside the
if.
- Prefer
=== and !== over == and !=. Strict comparison avoids type-conversion surprises.
- Put the most likely or most specific condition first in an
else if chain, and finish with a catch-all else.
- Choose the loop that matches the problem:
for for counted repetition, while for condition-driven repetition, do...while when one pass is mandatory.
- Keep loop bodies short. If a loop body grows beyond a handful of lines, consider moving the inner logic into a function in the next sub-module.
- Guard against infinite loops: before running any
while, confirm that something inside the body moves the condition towards false.
- Use
break to stop searching early once the answer is known; it saves work and makes intent clear.
- Use the ternary only for simple two-way choices and never nest ternaries; complex branching reads better as
if / else if.
- Name boolean variables as statements, such as
isLoggedIn, hasDiscount or isValid, so that if (isLoggedIn) reads like English.
- Avoid deep nesting. When an inner condition makes later code irrelevant, exit early with
continue or break instead of wrapping everything in more layers.
17. Practical project: student marks analyser
This small project uses conditions and loops to analyse a list of student marks. It is a complete, runnable script: paste it into an HTML file and open it in the browser, or run it in any JavaScript environment that supports console.log.
Step 1: set up the data
let students = [
{ name: "Asha", marks: [78, 85, 92] },
{ name: "Bilal", marks: [55, 61, 48] },
{ name: "Chitra", marks: [91, 88, 95] },
{ name: "Dev", marks: [34, 29, 40] }
];
Each student has a name and an array of three subject marks. Working with data shaped like this is exactly what you will do later in React when rendering lists from an API.
Step 2: write a helper condition for grading
function gradeFor(average) {
if (average >= 90) return "A";
if (average >= 75) return "B";
if (average >= 60) return "C";
if (average >= 35) return "D";
return "F";
}
Functions are covered fully in the next sub-module; for now, read this as a named, reusable condition chain.
Step 3: loop over students and compute results
let classTotal = 0;
let passCount = 0;
for (let i = 0; i < students.length; i++) {
let student = students[i];
let sum = 0;
for (let j = 0; j < student.marks.length; j++) {
sum += student.marks[j];
}
let average = sum / student.marks.length;
let grade = gradeFor(average);
let passed = average >= 35;
if (passed) {
passCount++;
}
classTotal += average;
console.log(
student.name + " - average: " + average.toFixed(1) +
", grade: " + grade +
(passed ? " (pass)" : " (fail)")
);
}
Step 4: print the class summary
let classAverage = classTotal / students.length;
console.log("--------------------------");
console.log("Class average: " + classAverage.toFixed(1));
console.log("Passed: " + passCount + " of " + students.length);
console.log(
passCount === students.length
? "Excellent: every student passed"
: (students.length - passCount) + " student(s) need support"
);
Complete output
Asha - average: 85.0, grade: B (pass)
Bilal - average: 54.7, grade: D (pass)
Chitra - average: 91.3, grade: A (pass)
Dev - average: 34.3, grade: F (fail)
--------------------------
Class average: 66.3
Passed: 3 of 4
1 student(s) need support
What this project demonstrates
- A
for loop nested inside another for loop to process marks per student.
- An accumulator pattern:
sum, classTotal and passCount all grow across iterations.
- A reusable condition chain for grading.
- A ternary used to build the final summary message.
toFixed(1) to round averages for display.
18. Practice Exercises
- Write a program that stores a number in a variable and prints "positive", "negative" or "zero" using an
if / else if / else chain.
- Write a
for loop that prints the multiplication table of 7 from 7 × 1 to 7 × 10, one line each.
- Given
let nums = [12, 5, 8, 130, 44, 3];, loop through the array and print only the numbers greater than 10, using continue to skip the rest.
- Loop from 1 to 50 and print "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number otherwise.
- Given an array of passwords, use a loop and conditions to print "strong" for passwords of 8 characters or more and "weak" for the others.
- Rewrite the following
if / else as a single ternary: if (temp > 30) { label = "hot"; } else { label = "cool"; }
- Write a
while loop that starts with let n = 1; and keeps doubling n until it exceeds 1000, then prints how many doublings happened.
- Write a
switch that maps a traffic light value ("red", "yellow", "green") to an action message, with a default for unknown values.
- Given two arrays of numbers of the same length, use nested loops-free logic (one loop with an index) to print the sum of each pair of matching elements.
- Write a loop that finds the largest number in
[3, 17, 9, 42, 5] without any built-in method, using only a loop, a condition and a variable that remembers the current maximum.
19. Interview Questions and Answers
What is the difference between == and ===?
== compares after converting the two values to a common type, so "5" == 5 is true. === compares both value and type without conversion, so "5" === 5 is false. In professional code, strict equality is the default choice because its behaviour is predictable; interviewers treat this as a baseline JavaScript question.
Which values are falsy in JavaScript?
Exactly six: false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy, including the strings "0" and "false", and empty arrays and objects. A popular follow-up is: "Is an empty array falsy?" The answer is no, it is truthy, which is why you check array.length for emptiness.
When would you use switch instead of if / else if?
When a single value is compared against several fixed options, such as a menu choice or a status code. switch reads cleanly and compares with strict equality. It cannot handle ranges or combined conditions, so if / else if remains the tool for checks like marks >= 75 or conditions joined with && and ||.
What happens if you omit break in a switch case?
Execution falls through into the next case and keeps running until it meets a break or the end of the switch. Multiple cases then execute for one matching value. Fall-through is a bug when accidental, but a deliberate technique when several case labels are stacked to share one block.
Explain the difference between for, while and do...while.
All three repeat a block. for bundles initialisation, condition and update in its header and suits a known number of iterations. while checks the condition before each pass and suits repetition of unknown length. do...while checks the condition after the body, guaranteeing at least one iteration even when the condition is false from the start.
What is an infinite loop and how do you avoid one?
A loop whose condition never becomes false, so it never ends. In a browser it freezes the tab. You avoid it by making sure the variable used in the condition is updated inside the loop and that the update moves towards the exit. With a for loop the update is built into the header; with while it is your responsibility.
What do break and continue do inside a loop?
break terminates the whole loop immediately and resumes execution after it; it is typically used to stop searching once a match is found. continue skips only the rest of the current iteration and jumps to the next pass; it is used to filter out unwanted items without leaving the loop.
What is the ternary operator and when should it be used?
It is a three-part expression, condition ? valueIfTrue : valueIfFalse, that returns one of two values. Use it for short, readable two-way choices, especially in assignments. Nested ternaries or ternaries containing multiple actions should be rewritten as if / else for readability.
Why do loops over arrays usually use i < array.length instead of i <= array.length?
Array indexes run from 0 to length - 1. Using <= makes the final iteration read array[length], which does not exist and yields undefined. This off-by-one error is one of the most common beginner bugs and a frequent interview trap.
What is short-circuit evaluation?
Logical operators stop evaluating as soon as the result is decided. In a && b, if a is false, b is never evaluated; in a || b, if a is true, b is never evaluated. This is used to guard code, for example checking that an object exists before reading its property in the same condition.
How are conditions used in React components?
React components decide what to display based on state, which is conditional logic in practice: a loading indicator shows while data is absent, and the data view shows once it arrives. Loops underlie rendering lists of items from arrays. Strong fundamentals in conditions and loops make these React patterns feel natural rather than mysterious.
Why is nesting conditions and loops deeply considered poor style?
Each nesting level multiplies the paths a reader must track, making bugs easier to hide. The preferred style is to exit early with continue, break or guard conditions, and to move inner logic into well-named functions. Shallow, flat logic is easier to test, read and maintain.
20. Quick Revision Checklist
- I can explain that every condition finally becomes a boolean:
true or false.
- I can write
if, else and chained else if blocks and know that only the first true branch runs.
- I know the comparison operators and always prefer
=== and !==.
- I know the three logical operators
&&, || and !, and how short-circuiting works.
- I can list the six falsy values from memory and know that empty arrays and objects are truthy.
- I can write a
switch with cases, break and default, and explain fall-through.
- I can write and read the ternary operator and know when not to use it.
- I can write a
for loop and explain initialisation, condition and update in order.
- I can loop through an array using
i < array.length without off-by-one errors.
- I can choose between
for, while and do...while based on the problem.
- I can use
break to exit a loop early and continue to skip an iteration.
- I can nest loops safely and use a boolean flag with
break to search one list inside another.
- I can spot and fix the classic mistakes: missing update in
while, = instead of ===, missing break, and empty-array truthiness.
21. Official Documentation and Further Reading
Conditions and loops are the JavaScript foundation that everything later in this course builds on. Before moving to the functions and scope sub-module, it is worth revisiting how these fundamentals connect to the React work ahead of you. The following resources from the course reading list put plain JavaScript knowledge in the context of modern React development:
Conclusion
Conditions and loops turn a calculator into a program. Conditions let your code answer questions and choose paths; loops let it repeat work without repetition in the source. Between them they cover decisions such as access control, grading, validation and filtering, and repetition such as processing lists, building summaries and searching data.
The skills from this page are cumulative with everything that follows. Functions and scope will wrap your condition chains into reusable named blocks. Arrays and objects will give your loops richer data to walk through. Modern JavaScript will offer cleaner iteration styles built on the same ideas. And in React, rendering decisions and list rendering are conditions and loops wearing a new syntax. Master the fundamentals here, slowly and honestly, and every later module becomes easier to read, easier to debug and faster to learn.
Learn more in the React JS Training course, or register for a course demo.