- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Conditions: Syntax, Usage, and Examples
Conditions in JavaScript let your code make decisions. They evaluate to either true or false and are the core of control flow in any program.
How to Use Conditions in JavaScript
Conditions are used inside control statements like if
, else
, else if
, switch
, and loops. They go inside parentheses and evaluate a boolean expression.
if (temperature > 30) {
console.log("It's hot outside.");
}
In this example, the code runs only if the condition (temperature > 30
) is true. If the condition is false, JavaScript skips the code block.
You can also use multiple conditions with logical operators:
if (isSunny && temperature > 20) {
console.log("Perfect day for a picnic.");
}
When to Use Conditions in JavaScript
Conditions help you control how your program behaves. You’ll use them anytime you want different outcomes depending on data, user actions, or system state.
1. Handling User Input
Conditions can validate input or control what feedback to give based on the user's choices.
let age = 17;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You must be 18 or older.");
}
2. Managing Application States
They’re helpful for managing app states, such as toggling a feature, checking if a user is logged in, or hiding/showing UI elements.
if (userLoggedIn) {
showDashboard();
} else {
redirectToLogin();
}
3. Running Code Based on Environment
Conditions also help in determining how your app runs depending on the environment.
if (process.env.NODE_ENV === "production") {
console.log("Running in production mode");
} else {
console.log("Development mode enabled");
}
Examples of JavaScript Conditions
Here are three practical examples that show how to use conditions in JavaScript.
Example 1: Simple Boolean Check
let isOnline = true;
if (isOnline) {
console.log("User is online");
} else {
console.log("User is offline");
}
This uses a basic condition to check if a variable is true or false.
Example 2: Comparing Values
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Keep practicing!");
}
This shows a common use of multiple conditions using else if
.
Example 3: Nested Conditions
let isMember = true;
let hasCoupon = false;
if (isMember) {
if (hasCoupon) {
console.log("You get 30% off!");
} else {
console.log("You get 10% off!");
}
} else {
console.log("Sign up to save!");
}
Nested conditions allow for more complex decision-making.
Learn More About JavaScript Conditions
Truthy and Falsy Values
In JavaScript, conditions aren’t just about true
or false
. Many values evaluate as truthy or falsy:
Falsy values include:
false
0
""
(empty string)null
undefined
NaN
Everything else is considered truthy, even things like '0'
or {}
.
let value = "";
if (value) {
console.log("This is truthy");
} else {
console.log("This is falsy"); // This will run
}
Logical Operators in Conditions
You can combine conditions using logical operators:
&&
(AND) – All conditions must be true.||
(OR) – At least one condition must be true.!
(NOT) – Reverses the truthiness.
let age = 25;
let hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("You can enter.");
}
The Ternary Operator
The ternary operator lets you write shorter conditional statements:
let age = 16;
let message = age >= 18 ? "Welcome!" : "Come back later.";
console.log(message);
It’s handy for simple if/else checks on one line.
Switch Statements
When you have many values to compare, switch statements can be cleaner than multiple if/else
blocks.
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("An apple a day!");
break;
case "banana":
console.log("Bananas are great.");
break;
default:
console.log("Unknown fruit");
}
Conditions Inside Loops
Conditions are also used inside loops to break, skip, or control behavior.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip when i is 3
}
console.log(i);
}
Real-World Example: Form Validation
function validateForm(name, email) {
if (!name || !email) {
return "Name and email are required.";
}
if (!email.includes("@")) {
return "Email must be valid.";
}
return "Form is valid!";
}
console.log(validateForm("Jada", "")); // Output: Name and email are required.
This example shows how conditions are used to handle common logic in real applications.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.