JavaScript Boolean Logic and Selection
In this module we explore the core concepts behind Boolean expressions, logical operators, and the if statement in JavaScript. Mastery of these topics is essential for writing reliable,…

What will be logged when the following code runs? let mark = 90; if ( mark >= 80 ) { grade = 'A'; } console.log( 'Your grade is ' + grade );
Why does the following code produce a ReferenceError? let mark = 79; if ( mark >= 80 ) { grade = ‘A’; console.log("congratulations"); } console.log( ‘Your grade is ’ + grade );
Identify the logical error in this snippet: if ( mark >= 80 ); { grade = ‘A’; } console.log( ‘Your grade is ’ + grade );
What is the output of the following code? let i = 1; let j = 2; let k = 3; if (i > j) if (i > k) console.log("A"); else console.log("B");
How can the previous code be modified so that it prints "B"?
When x = 2, y = 2, z = 0, what is printed by this code? if (x > 2) { if (y > 2) { z = x + y; console.log("z is " + z); } } else { console.log("x is " + x); }
If x = 3 and y = 3, what does the same code output?
Which of the following salaryIncrement implementations correctly follows the table: <1000 → $100, 1000‑1999 → $200, ≥2000 → $300?
What is the main advantage of initializing 'increment' to 200 before the if‑else chain, as shown in a later version?
In the switch example, why does the output remain "Welcome to SP" even though there is no break statement?
When ch is 'a', what will be printed by the following switch? switch (ch) { case 'a': console.log(ch); case 'b': console.log(ch); case 'c': console.log(ch); }
If a break is added after each case, what will be the output for ch = 'a'?
What value does y have after this switch executes? let x = 3, y = 3; switch (x + 3) { case 6 : y = 1; default: y += 1; }
If the case value is changed to 7 in the previous switch, what will y equal after execution?
Why is the following if‑else chain equivalent to the nested if version? if(score>=90.0) grade='A'; else if(score>=80.0) grade='B'; else if(score>=70.0) grade='C'; else if(score>=60.0) grade='D'; else grade='F';
What logical error occurs if the order of the else‑if statements is reversed, placing the <60 case first?
Which statement correctly determines whether an integer i is even using the % operator?
When can braces be omitted in an if‑else statement without changing behavior?
What is the result of evaluating the Boolean expression "(5 < 3) || (2 == 2)"?
Which of the following statements about the logical NOT operator is true?
Understanding JavaScript Boolean Logic and Conditional Selection
In this module we explore the core concepts behind Boolean expressions, logical operators, and the if statement in JavaScript. Mastery of these topics is essential for writing reliable, bug‑free code and for performing well in programming quizzes and interviews.
1. Boolean Operators: && and ||
JavaScript uses two primary logical operators to combine Boolean expressions:
- Logical AND (
&&) – Returnstrueonly if both operands are true. - Logical OR (
||) – Returnstrueif at least one operand is true.
Consider the following quiz question:
Given
num = 8, which expression correctly checks ifnumis divisible by both 2 and 3?
The correct answer is:
(num % 2 == 0) && (num % 3 == 0)
Explanation:
num % 2 == 0evaluates totruebecause 8 is divisible by 2.num % 3 == 0evaluates tofalsebecause 8 is not divisible by 3.- The
&&operator requires both sides to be true, so the whole expression isfalsefornum = 8.
Using || would incorrectly return true if only one condition were met, and omitting parentheses can lead to ambiguous or unintended results.
2. Variable Scope and Implicit Globals
JavaScript variables declared with let or const are block‑scoped. If you assign a value to an identifier that has not been declared, the engine creates an implicit global (in non‑strict mode) or throws a ReferenceError (in strict mode). This is a common source of bugs.
Quiz example:
What will be logged when the following code runs?
let mark = 90; if ( mark >= 80 ) { grade = 'A'; } console.log( 'Your grade is ' + grade );
The correct answer is "Your grade is A". Because the condition is true, the assignment grade = 'A' creates a global variable grade. The subsequent console.log can access it.
Contrast this with the next snippet:
let mark = 79; if ( mark >= 80 ) { grade = 'A'; console.log("congratulations"); } console.log( 'Your grade is ' + grade );
Here the condition is false, so the block never executes. The line grade = 'A' is never run, leaving grade undeclared. When the final console.log tries to read grade, a ReferenceError is thrown. This illustrates why you should always declare variables explicitly with let, const, or var.
3. The Dangerous Semicolon After if
A stray semicolon after an if condition terminates the conditional statement early, making the following block execute unconditionally. This subtle syntax error can produce logic that appears to work but behaves incorrectly.
Quiz question:
if ( mark >= 80 ); { grade = 'A'; } console.log( 'Your grade is ' + grade );
The correct answer identifies the error: The stray semicolon ends the if statement, making the block unconditional. As a result, grade = 'A' runs regardless of the condition, which may mask a failing test case.
Best practice: never place a semicolon directly after the condition parentheses. If you need an empty statement, write it on a separate line with a comment to make the intent clear.
4. Nested if Statements and the “Dangling Else” Problem
When you nest if statements without braces, JavaScript applies the dangling else rule: the else is associated with the nearest preceding if that lacks its own else. This can lead to unexpected output.
Consider this code:
let i = 1;
let j = 2;
let k = 3;
if (i > j)
if (i > k)
console.log("A");
else
console.log("B");
Because i > j is false, the outer if block is skipped entirely, and the inner if (and its else) are never evaluated. Consequently, no output is produced.
To force the else to belong to the outer if, you must use braces:
if (i > j) {
if (i > k) {
console.log("A");
} else {
console.log("B");
}
}
Now the else is clearly tied to the inner condition, and the code behaves as intended.
5. Practical Example: Multi‑Level Conditional Logic
Let’s analyze a more realistic scenario involving three variables x, y, and z:
if (x > 2) {
if (y > 2) {
z = x + y;
console.log("z is " + z);
}
} else {
console.log("x is " + x);
}
When x = 2 and y = 2, the outer condition x > 2 is false, so the else branch runs, printing "x is 2". The inner block never executes because its parent condition failed.
If we change the values to x = 3 and y = 3, the outer condition becomes true, the inner condition also true, and the code prints "z is 6" (since z = 3 + 3).
These examples demonstrate how the flow of execution depends on the hierarchy of conditions and why proper use of braces is crucial for readability and correctness.
6. Common Pitfalls and How to Avoid Them
- Missing variable declarations: Always declare variables with
letorconst. Implicit globals can cause hard‑to‑track bugs. - Stray semicolons after
if: A trailing semicolon turns the conditional into a no‑op. Use a linter or enableeslintrules likeno-extra-semito catch them. - Ambiguous
elsebinding: Use braces even for single‑line blocks. This eliminates the dangling‑else confusion. - Incorrect logical operators: Remember that
&&requires all conditions to be true, while||needs only one. Choose the operator that matches the intended logic. - Operator precedence: Parentheses clarify evaluation order. For complex expressions, always wrap each comparison in its own parentheses.
7. Quick Reference Cheat Sheet
condition && condition– Both must be true.condition || condition– At least one must be true.if (expr) statement– Executesstatementwhenexpris truthy.if (expr) { … } else { … }– Provides an alternative path.- Never place a semicolon directly after the
ifparentheses. - Always use braces
{ }for nestedifstatements. - Declare variables with
letorconstbefore using them.
8. Practice Exercises
Try rewriting the following snippets to fix the errors described:
- ```js
let score = 75;
if (score >= 90) {
grade = 'A';
}
console.log('Grade:', grade);
```
Identify the problem and correct it. - ```js
let a = 5;
if (a > 3);
{
console.log('Inside block');
}
```
Explain why the console always logs and remove the bug. - ```js
let x = 1, y = 2;
if (x > y)
if (x > 0)
console.log('Positive');
else
console.log('Negative');
```
Modify the code so that theelsebelongs to the outerif.
After completing these exercises, you will have reinforced the concepts covered in this module.
9. SEO‑Friendly Summary
Understanding JavaScript Boolean logic, proper if syntax, and variable scope is vital for developers aiming to write clean, maintainable code. By mastering the use of &&, ||, avoiding stray semicolons, and always declaring variables, you reduce runtime errors such as ReferenceError and improve code readability. These skills are frequently tested in quizzes, technical interviews, and real‑world projects.
For further reading, explore topics like truthy and falsy values, short‑circuit evaluation, and strict mode to deepen your JavaScript expertise.
