JavaScript Conditionals — Complete Guide with Examples

JavaScript Conditionals — Complete Guide with Examples

JavaScript Conditionals — Complete Guide with Examples | TipsInLearning
Beginner

JavaScript Conditionals

Master conditional statements: learn how to use if, else, else if, and switch to control your code flow. Make decisions in your programs with comparison and logical operators.

10 min read Essential concept

What You'll Learn

How to use if, else, and else if statements
Switch statements for cleaner code
Comparison operators (==, ===, !=, !==, >, <, >=, <=)
Logical operators (&&, ||, !)
Ternary operator for concise conditions
Best practices and common pitfalls

The if Statement

The if statement executes code only when a specified condition is true. It's the foundation of decision-making in programming.

Syntax

JavaScript
if (condition) { // code to be executed if condition is true }

Example

JavaScript
let age = 18; if (age >= 18) { // You are an adult }

The else Statement

The else statement executes code when the if condition is false. Use it to handle the alternative case.

Syntax

JavaScript
if (condition) { // code if true } else { // code if false }

Example

JavaScript
let age = 15; if (age >= 18) { // You are an adult } else { // You are a minor }

The else if Statement

Test multiple conditions in sequence using else if. The first true condition will execute, and the rest are skipped.

Syntax

JavaScript
if (condition1) { // code if condition1 is true } else if (condition2) { // code if condition2 is true } else { // code if all conditions are false }

Example

JavaScript
let score = 75; if (score >= 90) { // Grade: A } else if (score >= 80) { // Grade: B } else if (score >= 70) { // Grade: C } else { // Grade: F }

The switch Statement

Use switch for cleaner code when comparing one value against many options. It's more efficient than multiple else if statements.

Syntax

JavaScript
switch (expression) { case value1: // code if expression === value1 break; case value2: // code if expression === value2 break; default: // code if no match }
Important: Always include break after each case to prevent fall-through, unless you want that behavior intentionally.

Example

JavaScript
let day = 3; let dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; default: dayName = "Weekend"; } // dayName is "Wednesday"

Comparison Operators

These operators are used in conditions to compare values:

Operator Description Example Result
== Equal (loose comparison) 5 == "5" true
=== Strictly equal (type matters) 5 === "5" false
!= Not equal 5 != 3 true
!== Strictly not equal 5 !== "5" true
> Greater than 10 > 5 true
< Less than 3 < 7 true
>= Greater than or equal 5 >= 5 true
<= Less than or equal 3 <= 8 true
Best Practice: Always use === instead of == for strict comparison. This prevents unexpected type conversion bugs.

Logical Operators

Combine multiple conditions using logical operators:

Operator Name Description Example
&& AND Both conditions must be true age > 18 && hasLicense
|| OR At least one condition must be true isFriday || isSaturday
! NOT Reverses/negates the condition !isRaining

Example with Logical Operators

JavaScript
let age = 25; let hasLicense = true; if (age >= 18 && hasLicense) { // You can drive } else { // You cannot drive } // Using OR operator if (day === "Saturday" || day === "Sunday") { // It's the weekend! } // Using NOT operator if (!isRaining) { // It's a beautiful day! }

Ternary Operator

A shorthand syntax for simple if-else statements. Also called the conditional operator.

Syntax

condition ? valueIfTrue : valueIfFalse

Example

JavaScript
let age = 20; let status = age >= 18 ? "Adult" : "Minor"; // status is "Adult" // Nested ternary (use with caution for readability) let score = 85; let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"; // grade is "B"
Tip: The ternary operator is great for simple assignments, but avoid nesting multiple ternary operators as it reduces readability. Use if-else for complex logic.

Common Mistakes to Avoid

  • Using == instead of === for comparison
  • Forgetting break in switch cases
  • Using = instead of == or === in conditions
  • Not using curly braces for readability
  • Nesting too many conditions without breaking into functions

Key Takeaways

if

Execute code when a condition is true

else

Handle the alternative case when condition is false

===

Always use strict equality for safe comparisons

&&

Combine conditions where all must be true

switch

Cleaner alternative to multiple else if statements

?:

Use ternary operator for simple conditional assignments

Frequently Asked Questions

What are JavaScript conditionals?

JavaScript conditionals are statements that execute different code based on conditions. They allow your program to make decisions and follow different paths of execution based on boolean (true/false) values. The main types are if, else, else if, and switch statements.

What is the difference between == and ===?

== (loose equality) compares values with automatic type conversion, while === (strict equality) compares both value and type. For example, 5 == "5" returns true, but 5 === "5" returns false. It's best practice to always use === to avoid unexpected type coercion bugs.

When should I use switch instead of if-else?

Use switch when comparing a single value against many different options. It's cleaner and more readable than multiple else if statements. However, if-else is better for complex conditions involving ranges or multiple different variables. Switch uses === for comparison, so type matters.

What is the ternary operator?

The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand for simple if-else statements. It's useful for assigning values based on a condition, but avoid nesting multiple ternary operators as it reduces code readability. Use regular if-else for complex logic.

What are logical operators in JavaScript?

Logical operators (&&, ||, !) are used to combine or negate conditions. && (AND) requires all conditions to be true, || (OR) requires at least one to be true, and ! (NOT) reverses/negates a condition. They're essential for building complex conditional logic.

What happens if I forget the break statement in a switch case?

Without break, execution "falls through" to the next case and continues executing code until it hits a break or the switch ends. This is usually a bug, but sometimes intentional for fall-through logic. Always include break unless you explicitly want fall-through behavior.

Post a Comment