Understanding Conditionals
Conditionals are statements that allow you to make decisions and execute different blocks of code based on whether certain conditions are true or false. Conditionals are a fundamental concept that enables your code to respond dynamically to various situations.
1. Making Decisions
Conditionals are used to create decision-making structures in your code. They enable your program to choose different paths of execution based on whether specific conditions are met.
2. If Statements
The most basic form of conditional is the if
statement. It evaluates a condition and, if true, executes a specified block of code. If false, the code inside the block is skipped.
if (condition) {
// Code to execute if condition is true
}
3. Else Statements
The else
statement provides an alternative block of code to execute when the condition is false, covering both “if” and “else” scenarios.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
4. Else-If Statements
Else if
statements evaluate additional conditions when you have multiple conditions to check, executing the block of the first true condition.
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if no conditions are true
}
5. Switch Statements
Switch
statements test a variable against multiple values and execute different code blocks based on the matching value.
switch (variable) {
case value1:
// Code to execute for value1
break;
case value2:
// Code to execute for value2
break;
default:
// Code to execute if no cases match
}
6. Ternary Operator
In some languages like JavaScript, the ternary operator (condition ? expressionIfTrue : expressionIfFalse
) provides a shorthand for simple conditional expressions.
var result = (condition) ? "Value if true" : "Value if false";
Conditionals are a powerful tool for controlling the flow of your program based on different situations. They allow your code to adapt and respond to changing conditions, making your applications more dynamic and interactive.
JavaScript Conditional Examples
1. If Statement
var age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
2. If-Else Statement
var temperature = 25;
if (temperature > 30) {
console.log("It's hot outside.");
} else {
console.log("It's not too hot.");
}
3. Else-If Statement
var grade = 85;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) {
console.log("B");
} else if (grade >= 70) {
console.log("C");
} else {
console.log("F");
}
4. Switch Statement
var day = "Monday";
switch (day) {
case "Monday":
console.log("It's the start of the week.");
break;
case "Friday":
console.log("It's the end of the week.");
break;
default:
console.log("It's a regular day.");
}
5. Ternary Operator
var isMorning = true;
var greeting = isMorning ? "Good morning!" : "Hello!";
console.log(greeting);