Conditional statements are fundamental in programming as they allow you to execute different code based on certain conditions. In JavaScript, the primary conditional statements are if
, else if
, else
, and switch
. This section will cover each of these in detail, along with practical examples and exercises.
if
Statement
if
StatementThe if
statement is used to execute a block of code only if a specified condition is true.
Syntax
Example
Explanation
condition
: This is an expression that evaluates totrue
orfalse
.- If the condition is
true
, the code inside the block{}
is executed. - If the condition is
false
, the code inside the block is skipped.
else
Statement
else
StatementThe else
statement is used to execute a block of code if the condition in the if
statement is false
.
Syntax
if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }
Example
let age = 16; if (age >= 18) { console.log("You are eligible to vote."); } else { console.log("You are not eligible to vote."); }
Explanation
- If the
if
condition isfalse
, the code inside theelse
block is executed.
else if
Statement
else if
StatementThe else if
statement is used to specify a new condition if the first condition is false
.
Syntax
if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if condition2 is true } else { // block of code to be executed if both condition1 and condition2 are false }
Example
let score = 85; if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else if (score >= 70) { console.log("Grade: C"); } else { console.log("Grade: F"); }
Explanation
- Multiple
else if
statements can be used to check various conditions. - The
else
block is optional and will execute if none of the conditions aretrue
.
switch
Statement
switch
StatementThe switch
statement is used to perform different actions based on different conditions. It is an alternative to using multiple else if
statements.
Syntax
switch (expression) { case value1: // block of code to be executed if expression === value1 break; case value2: // block of code to be executed if expression === value2 break; // more cases default: // block of code to be executed if expression doesn't match any case }
Example
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; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } console.log(dayName); // Output: Wednesday
Explanation
expression
: This is evaluated once and compared with the values of eachcase
.case value
: If the expression matchesvalue
, the corresponding block of code is executed.break
: This statement terminates theswitch
block. If omitted, the nextcase
will be executed regardless of the match.default
: This block is executed if no matchingcase
is found. It is optional.
Practical Exercises
Exercise 1: Simple if-else
Statement
Write a program that checks if a number is positive, negative, or zero.
let number = prompt("Enter a number:"); if (number > 0) { console.log("The number is positive."); } else if (number < 0) { console.log("The number is negative."); } else { console.log("The number is zero."); }
Exercise 2: Grade Calculator
Write a program that assigns a grade based on a score using if-else if-else
statements.
let score = prompt("Enter your score:"); if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else if (score >= 70) { console.log("Grade: C"); } else if (score >= 60) { console.log("Grade: D"); } else { console.log("Grade: F"); }
Exercise 3: Day of the Week
Write a program that prints the day of the week based on a number using a switch
statement.
let day = prompt("Enter a number (1-7):"); let dayName; switch (parseInt(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; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } console.log(dayName);
Common Mistakes and Tips
- Forgetting the
break
statement inswitch
cases: This can lead to "fall-through" where multiple cases are executed. - Using assignment
=
instead of equality==
or===
in conditions: This can cause unexpected behavior. - Not handling all possible conditions: Always consider adding an
else
ordefault
case to handle unexpected values.
Conclusion
In this section, we covered the basics of conditional statements in JavaScript, including if
, else if
, else
, and switch
. These constructs allow you to control the flow of your program based on different conditions. Practice the exercises provided to reinforce your understanding and prepare for more advanced topics.
JavaScript: From Beginner to Advanced
Module 1: Introduction to JavaScript
- What is JavaScript?
- Setting Up Your Development Environment
- Your First JavaScript Program
- JavaScript Syntax and Basics
- Variables and Data Types
- Basic Operators
Module 2: Control Structures
Module 3: Functions
- Defining and Calling Functions
- Function Expressions and Arrow Functions
- Parameters and Return Values
- Scope and Closures
- Higher-Order Functions
Module 4: Objects and Arrays
- Introduction to Objects
- Object Methods and 'this' Keyword
- Arrays: Basics and Methods
- Iterating Over Arrays
- Array Destructuring
Module 5: Advanced Objects and Functions
- Prototypes and Inheritance
- Classes and Object-Oriented Programming
- Modules and Import/Export
- Asynchronous JavaScript: Callbacks
- Promises and Async/Await
Module 6: The Document Object Model (DOM)
- Introduction to the DOM
- Selecting and Manipulating DOM Elements
- Event Handling
- Creating and Removing DOM Elements
- Form Handling and Validation
Module 7: Browser APIs and Advanced Topics
- Local Storage and Session Storage
- Fetch API and AJAX
- WebSockets
- Service Workers and Progressive Web Apps (PWAs)
- Introduction to WebAssembly
Module 8: Testing and Debugging
Module 9: Performance and Optimization
- Optimizing JavaScript Performance
- Memory Management
- Efficient DOM Manipulation
- Lazy Loading and Code Splitting
Module 10: JavaScript Frameworks and Libraries
- Introduction to React
- State Management with Redux
- Vue.js Basics
- Angular Basics
- Choosing the Right Framework