Ternary operators in JavaScript without an else
First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
- use ternary expressions only when you have a variable on the left side of the
=
that is to be assigned the return value - only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
- each part of the expression (after ? and after : ) should return a value without side effects (the expression
x = true
returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)
In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ;
, where you use a ternary expression to set the value of x
, you can use this:
condition && (x = true);
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
UPDATE
In relation to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
If without else ternary operator
No, you cannot do that.
Instead try this:
if(bool1 && bool2) voidFunc1();
Javascript Ternary operator with empty else
Answer to your real question in the comments:
all2.forEach(function (e) {
e.getAttribute("class") && only.push(e.getAttribute("class"));
});
Conditional (ternary) operator is going directly to else option
let tipoUser = parseInt(sessionStorage.getItem("TipoUser"))
How do you use the ? : (conditional) operator in JavaScript?
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
This can be shortened with the ?:
like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
They can even be chained:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
JavaScript shorthand if statement, without the else portion
you can use &&
operator - second operand expression is executed only if first is true
direction == "right" && slideOffset += $(".range-slide").width()
in my opinion if(conditon) expression
is more readable than condition && expression
How to not return a value from the last ternary operator?
How to not return a value from the last ternary operator?
No, you can't, the last part of a ternary operator is required. To accomplish that, you need if-else
blocks.
if (col_1 === 0) {
result = 0;
} else if (col_1 >= 1) {
result = col_1 - 1;
}
An alternative is using the logical operator &&
Like I said, the last part is required
(col_1 === 0) ? 0 : (col_1 >= 1 && col_1 - 1);
var col_1 = 0;var result = (col_1 === 0) ? 0 : (col_1 >= 1 && col_1 - 1);console.log(result);
col_1 = 5;result = (col_1 === 0) ? 0 : (col_1 >= 1 && col_1 - 1);console.log(result);
col_1 = 3;result = (col_1 === 0) ? 0 : (col_1 >= 1 && col_1 - 1);console.log(result);
col_1 = -1;result = (col_1 === 0) ? 0 : (col_1 >= 1 && col_1 - 1); // This case will always return false because 'col_1 < 0' // Here you can check for that valueconsole.log("You need to check this situation: ", result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Is it possible to write one way ternary operator?
I guess you could do something like:
function sumFibs(num) {
let a = 0, b = 1, fib = 0;
let i = 0;
let fibArr = []
let result = 0;
while(fib <= num){
fibArr.push(fib)
a = b;
b = fib;
fib = a+b;
}
for(let i = 0; i<fibArr.length; i++) {
(fibArr[i] % 2 !== 0) ? (result += fibArr[i]) : null;
}
console.log(result)
return result;
}
But this doesn't seem to add much value, only confusion. Note that ternary operator is often used as an assignment, not a control flow statement.
To be more specific this is the part that was changed. Note that there is no way of having something like {condition} ? value :
syntax wise. You always have to return an expression after the colon.
(fibArr[i] % 2 !== 0) ? (result += fibArr[i]) : null;
Related Topics
Syntax for an Async Arrow Function
Easy to Understand Definition of "Asynchronous Event"
Use Dynamic (Variable) String as Regex Pattern in JavaScript
Closure in JavaScript - Whats Wrong
Uncaught Typeerror: Cannot Read Property 'Msie' of Undefined - Jquery Tools
React: Why Child Component Doesn't Update When Prop Changes
Change the Content of a Div Based on Selection from Dropdown Menu
How to Change HTML Object Element Data Attribute Value in JavaScript
HTML Drag and Drop on Mobile Devices
Make Checkbox Behave Like Radio Buttons with JavaScript
Difference Between "Module.Exports" and "Exports" in the Commonjs Module System
Export JavaScript Data to CSV File Without Server Interaction
Detect When an Image Fails to Load in JavaScript
Difference Between the 'Controller', 'Link' and 'Compile' Functions When Defining a Directive
Javascript: How to Dynamically Create Nested Objects Using Object Names Given by an Array
Jquery - Sticky Header That Shrinks When Scrolling Down
Removing Page Title and Date When Printing Web Page (With CSS)