Conditional statements: Making decisions in JavaScript
Photo: Conditional Statements - ReactedNode
What You Should Know
- What JavaScript is and how to write basic statements.
- How to run JavaScript in the browser.
- What variables are and how to store values in them.
What You Will Learn
- How to make decisions in your JavaScript code using conditional statements.
- How do the if, else, and else if statements work?
- What nested conditionals are and how to use them.
Key Concepts
What Is a Conditional Statement?
A conditional statement is a way to make decisions in a program. Based on whether certain conditions are true or false, your program can choose to execute specific blocks of code. Imagine your program reaches a point where it needs to decide which path to take - conditional statements provide the map.
The if statement
The if statement tells the program: "If this specific condition is true, then execute the code inside the following curly braces {} (code block)." If the condition is false, then skip the code block.
Syntax:
Example:
The else statement
We use the else block to run code when the condition is not true. The else block always accompanies an if statement and executes its block of code when the if statement's condition is false.
Syntax:
Example:
The else if statement
We use the else if statement when we want to check for more than one condition. It allows us to chain multiple conditions together.
Syntax:
Example:
Nesting conditional statements
We can place conditional statements inside other conditional statements. This is called nesting. It allows for more intricate and layered decision-making logic.
Why it matters
- Conditional statements enable programs to think and make decisions.
- Without conditional statements, programs would perform the same task every time, regardless of the circumstances.
- Conditional statements are the foundation for creating interactive and dynamic behavior in websites, games, and apps.