đź’Ż Inline If-else in Javascript
The shorthand version of the if-else
statement in JavaScript is called the ternary operator. It is a concise way to write simple if-else
statements and is structured like this:
condition ? expressionIfTrue : expressionIfFalse;
Explanation:
condition
: This is the condition you want to evaluate (just like in a normalif
statement).?
: Separates the condition from the expressions.expressionIfTrue
: This expression is executed if the condition istrue
.:
: Separates thetrue
andfalse
expressions.expressionIfFalse
: This expression is executed if the condition isfalse
.
Example:
let age = 18;
let message = age >= 18 ? 'You are an adult.' : 'You are a minor.';
console.log(message); // Output: "You are an adult."
In this example:
- If
age >= 18
istrue
, the value ofmessage
will be"You are an adult."
- If
age >= 18
isfalse
, the value ofmessage
would be"You are a minor."
Gotchas:
-
Readability: Ternary operators are great for simple conditions, but for more complex logic or nested conditions, they can make your code hard to read. It’s usually better to use full
if-else
blocks for complex logic. -
Avoid Overuse: Too many ternary operators in a row or deeply nested ternary operators can quickly become difficult to understand.
Complex Example:
let score = 85;
let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
console.log(grade); // Output: "B"
In this case, the nested ternary operator evaluates multiple conditions in a compact way. But again, for more complex logic, standard if-else
blocks are often more readable.
More General
In JavaScript, if queries are a key way to make decisions in code by testing an expression for true or false. The syntax is very simple:
Basic syntax:
if (condition) {
// Code that is executed if the condition is true
} else {
// Code that is executed if the condition is false
}
Here is an example:
let score = 75;
if (score >= 90) {
console.log('Grade: Very good');
} else if (score >= 75) {
console.log('Grade: Good');
} else {
console.log('Grade: Needs improvement');
}
1. How the if query works
The if query checks the specified condition. If the condition is true, the code inside the first block (if
) is executed. If it is false, the else
block is executed (if present). It is also possible to check multiple conditions using else if
.
- Truth values: In JavaScript, anything that can be interpreted as “true” or “false” is called truthy or falsy.
- Falsy values in JavaScript:
false
,0
,""
(empty string),null
,undefined
,NaN
. - All other values ​​are considered truthy.
Example with falsy values:
let value = 0;
if (value) {
console.log('Value is true');
} else {
console.log('Value is false');
}
Since 0
is a falsy value, the output will be “Value is false”.
2. Gotchas in JavaScript with if-Queries
When working with if
-Queries in JavaScript, there are a few pitfalls to keep in mind:
2.1. Type Coercion
JavaScript is a weakly typed language, which means that it tries to automatically convert values ​​to another type when it checks a condition. This can lead to unexpected results.
if (0 == false) {
console.log('0 is equal to false');
}
Result: “0 is equal to false” is printed because the value 0
is converted to a falsy value, which results in a true comparison in the weak comparison operation (==
).
Solution: Strict comparison with ===
Use the strict comparison operator ===
to not let the types be automatically converted.
if (0 === false) {
console.log('This will not be done');
} else {
console.log('0 is not equal to false');
}
Result: “0 is not equal to false”, because the strict comparison also takes the data type into account.
2.2. Undeclared variables
In JavaScript, you can access undeclared variables, which leads to an error.
if (myVariable) {
console.log('This variable exists');
}
If myVariable
is not declared, you will receive a ReferenceError. To avoid this, you should always declare variables or use typeof
to check their existence.
if (typeof myVariable !== 'undefined') {
console.log('Variable is declared');
}
2.3. Nested ifs
If if
queries are nested too much, the code can become difficult to read and maintain. This is called “callback hell” or “pyramid of doom”.
if (a > 5) {
if (b < 10) {
if (c === 3) {
console.log('Complex nested case');
}
}
}
Solution: Use logical operators
You can avoid such nesting by using logical operators like &&
and ||
:
if (a > 5 && b < 10 && c === 3) {
console.log('More elegant solution');
}
2.4. The lack of an else
branch
There are cases where you don’t consider what happens if the condition is false, which can lead to unintended gaps in the logic.
let temperature = 30;
if (temperature > 25) {
console.log("It's hot");
}
// No action if temperature <= 25
It can be useful to always add an else
branch to handle unexpected scenarios:
if (temperature > 25) {
console.log("It's hot");
} else {
console.log("It's comfortable or cool");
}
2.5. Be careful with empty arrays and objects
In JavaScript, empty arrays and empty objects are truthy, even if they look “empty”.
if ([]) {
console.log('An empty array is considered true');
}
if ({}) {
console.log('An empty object is considered true');
}
This is a common misconception, especially for developers coming from languages ​​where empty structures can be falsy.
3. Shorthand with the ternary operator
The ternary operator is a shorthand for simple if
queries.
let age = 20;
let access = (age >= 18) ? 'Access allowed' : 'Access denied';
console.log(access);
This replaces a simple if
query with a more compact and clear solution when only one condition and one alternative are required.
4. If query without brackets
It is possible in JavaScript to write an if
query without curly brackets {}
if it only contains a single command. However, this can lead to hard-to-read and error-prone code:
if (age >= 18) console.log('Access allowed');
Best Practice: Always use parentheses
To avoid misunderstandings and maintenance issues, it is a good practice to always use parentheses, even for single-line statements:
if (age >= 18) {
console.log('Access allowed');
}
Summary
-
If queries enable decision logic in JavaScript.
-
Be careful about type conversions and use strict comparison (
===
). -
Avoid nesting too deeply by using logical operators.
-
Be aware of the behavior of truthy and falsy values, especially for empty arrays and objects.
-
Use the ternary operator for simple conditions, but don’t overdo it.
Use these tips to make sure your if
queries in JavaScript work correctly and efficiently.