- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript If Statement: Syntax, Usage, and Examples
In JavaScript, an if statement is a control structure that executes (or skips) blocks of code based on specified conditions.
How to Use the If Statement in JavaScript
JavaScript If Statement
The syntax for the if statement in JavaScript involves the if
keyword followed by a condition enclosed in parentheses and a block of code enclosed in curly braces that executes if the condition is true.
if (condition) {
// Code to execute if condition is true
}
if
: The keyword that initiates an if statement.condition
: A boolean expression to evaluate totrue
orfalse
. If the condition evaluates totrue
, the if statement’s body executes. If the condition evaluates tofalse
, the if statement’s body gets skipped.
JavaScript if statements are often used within HTML documents to dynamically modify web page elements based on user interaction.
<!DOCTYPE html>
<html>
<head>
<script>
function toggleText() {
let text = document.getElementById("message");
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
</script>
</head>
<body>
<button onclick="toggleText()">Toggle Message</button>
<p id="message" style="display:none;">Hello, this is a dynamic message!</p>
</body>
</html>
JavaScript If-Else Statement
You can expand the if statement to include an else clause. An if-else statement’s else block executes if the condition evaluates to false.
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
if
: The keyword that initiates an if statement.condition
: A boolean expression to evaluate totrue
orfalse
.else
: The keyword that initiates an else clause.
JavaScript If-Else-If-Else Statements
Finally, an if statement can also include else if and a condition in parentheses to check for another condition. As soon as a condition evaluates to true, the block of code below the condition executes.
A conditional statement can have an infinite number of else if clauses. The else clause at the end executes if none of the conditions evaluate to true.
if (condition) {
// Code executes if condition is true
} else if (anotherCondition) {
// Code executes if the first condition is false and another condition is true
} else {
// Code executes if all conditions are false
}
if
: The keyword that initiates an if statement.condition
: A boolean expression to evaluate totrue
orfalse
.else if
: The keywords that initiate an else if clause.anotherCondition
: A boolean expression to evaluate totrue
orfalse
if the previous condition evaluated tofalse
.else
: The keyword that initiates an else clause.
While if-else
statements allow multiple condition checks, sometimes a switch statement is a more readable alternative when dealing with multiple conditions based on a single value.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Weekend is near!");
break;
default:
console.log("Another regular day.");
}
When to Use the If Statement in JavaScript
If statements and other conditional statements are useful whenever you need to make decisions based on conditions. This decision-making capability is key to creating dynamic and interactive applications in JavaScript. Conditional statements play a crucial role in web development, allowing developers to create dynamic and interactive experiences.
Making Decisions
You can use a conditional statement to decide which code to execute based on dynamic conditions at runtime.
let hour = new Date().getHours();
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good day!");
}
Handling User Input
Also, you can use a conditional statement to validate user input, checking for correctness or completeness before processing.
let email = "user@example.com";
if (email.includes("@")) {
console.log("Email is valid.");
} else {
console.log("Please enter a valid email.");
}
The const
keyword is often used for variables that should not be reassigned, such as an email address.
const email = "user@example.com"; // Using const since the variable won't be reassigned
if (email.includes("@")) {
console.log("Email is valid.");
} else {
console.log("Please enter a valid email.");
}
When working with user inputs, it's crucial to check for NaN
(Not-a-Number) values in numerical fields.
let userInput = Number("abc"); // Trying to convert a string to a number
if (isNaN(userInput)) {
console.log("Invalid number input.");
} else {
console.log("Valid number:", userInput);
}
Handling Scenarios
If statements enable programs to handle different scenarios, like the success or failure of an operation.
// Handling success or failure
let operationSuccessful = false
if (operationSuccessful) {
console.log("The operation was successful.");
} else {
console.log("The operation failed.");
}
JavaScript often interacts with APIs that return data in JSON format. Conditional statements can check for valid JSON responses.
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
if (data.success) {
console.log("Data loaded:", data);
} else {
console.log("Failed to load data.");
}
});
Examples of the If Statement in JavaScript
Here are some examples of real-world scenarios for using a conditional statement:
Age Checks
A video platform might use an if statement to check a user’s age and recommend age-appropriate content.
let age = 20;
if (age >= 18) {
showAdultContent();
} else {
showChildContent();
}
Feature Toggling
An application like Mimo might use if statements to control the visibility or functionality of features in applications. Feature toggles are especially useful during development or for A/B testing.
let featureEnabled = true;
if (featureEnabled) {
console.log("New feature is now available.");
} else {
console.log("Feature is currently disabled.");
}
Feature toggling in JavaScript is often combined with CSS to show or hide elements dynamically.
.hidden {
display: none;
}
const featureEnabled = true;
if (featureEnabled) {
document.getElementById("featureBox").classList.remove("hidden");
} else {
document.getElementById("featureBox").classList.add("hidden");
}
Login Processes
Applications with user accounts might use conditional statements to authenticate users. This typically involves comparing a stored password hash with the hashed user input.
// Authenticating a user
let storedPasswordHash = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5"; // Example hash
let inputPassword = "12345";
if (hashFunction(inputPassword) === storedPasswordHash) {
console.log("Access granted.");
} else {
console.log("Access denied. Incorrect password.");
}
In more advanced authentication systems, developers may use a constructor to define user objects.
class User {
constructor(username, password) {
this.username = username;
this.password = password;
}
authenticate(inputPassword) {
return this.password === inputPassword;
}
}
const user1 = new User("johnDoe", "securePassword123");
if (user1.authenticate("securePassword123")) {
console.log("Access granted.");
} else {
console.log("Access denied.");
}
Learn More About the If Statement in JavaScript
Nested If Statements and Nested If-Else Statements
Nested if statements and nested if-else statements provide a way to make more detailed checks. Nesting conditional statements is useful when decisions need several layers of logic.
let score = 85;
if (score >= 50) {
if (score >= 80) {
console.log("Grade: A");
} else {
console.log("Grade: B");
}
} else {
console.log("Failed");
}
When using nested if statements, it’s important to properly structure the code block for readability and maintainability.
let score = 85;
if (score >= 50) {
if (score >= 80) {
console.log("Grade: A");
} else {
console.log("Grade: B");
}
} else {
console.log("Failed");
}
// Each condition contains a separate **code block** for execution.
Logical Operators and Multiple Conditions
In JavaScript, combining multiple conditions within an if statement is often necessary to handle complex decision-making processes. Often, logical operators such as &&
(and), ||
(or), and !
(not) can help evaluate multiple boolean expressions in a single line.
let temperature = 30, sunny = true;
if (temperature > 25 && sunny) {
console.log("Let's go to the beach!");
} else {
console.log("It's not a good day for the beach.");
}
Like JavaScript, Java also supports logical operators such as &&
, ||
, and !
for complex conditions.
int temperature = 30;
boolean sunny = true;
if (temperature > 25 && sunny) {
System.out.println("Let's go to the beach!");
} else {
System.out.println("It's not a good day for the beach.");
}
Short-circuit Evaluation
In JavaScript, short-circuit evaluation utilizes logical operators to check conditions more efficiently. This technique stops the evaluation of expressions as soon as the outcome is clear, optimizing performance.
let loggedIn = true;
if (loggedIn && user.hasAccess()) {
console.log("User has access.");
} else {
console.log("Access denied.");
}
The console.log
method is commonly used for debugging and printing messages to the browser console.
let loggedIn = true;
if (loggedIn && user.hasAccess()) {
console.log("User has access.");
} else {
console.log("Access denied.");
}
Conditional (Ternary) Operator
The conditional (ternary) operator is a concise way to express simple if-else statements. It takes requires a condition followed by a question mark (?
), the expression to execute if the condition is true
, and a colon (:
) followed by the expression to execute if the condition is false
.
let age = 20;
let status = (age >= 18) ? "adult" : "minor";
console.log(status);
The ternary operator in JavaScript is similar to Python’s conditional expression.
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # Output: adult
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.