Ternary operator within parentheses -- What does this do? [duplicate] - javascript

What is the ?: (question mark and colon operator aka. conditional or "ternary") operator and how can I use it?

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.

I want to add some to the given answers.
In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.
Instead of:
var welcomeMessage = 'Hello ' + (username ? username : 'guest');
You can use:
var welcomeMessage = 'Hello ' + (username || 'guest');
This is Javascripts equivallent of PHP's shorthand ternary operator ?:
Or even:
var welcomeMessage = 'Hello ' + (username || something || maybethis || 'guest');
It evaluates the variable, and if it's false or unset, it goes on to the next.

It's called the 'ternary' or 'conditional' operator.
Example
The ?: operator can be used as a
shortcut for an if...else statement.
It is typically used as part of a
larger expression where an if...else
statement would be awkward. For
example:
var now = new Date();
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");
The example creates a string
containing "Good evening." if it is
after 6pm. The equivalent code using
an if...else statement would look as
follows:
var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
greeting += " evening.";
else
greeting += " day.";
From MSDN JS documentation.
Basically it's a shorthand conditional statement.
Also see:
Operator precedence with Javascript Ternary operator
Wikipedia

It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator".
If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $ symbol.
To answer your question, conditional operators replace simple if statements. An example is best:
var insurancePremium = age > 21 ? 100 : 200;
Instead of:
var insurancePremium;
if (age > 21) {
insurancePremium = 100;
} else {
insurancePremium = 200;
}

Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else :
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
Equivalent to:
function example() {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
More details is here

z = (x == y ? 1 : 2);
is equivalent to
if (x == y)
z = 1;
else
z = 2;
except, of course, it's shorter.

Ternary Operator
Commonly we have conditional statements in Javascript.
Example:
if (true) {
console.log(1)
}
else {
console.log(0)
}
# Answer
# 1
but it contain two or more lines and cannot assign to a variable.
Javascript have a solution for this Problem Ternary Operator.
Ternary Operator can write in one line and assign to a variable.
Example:
var operator = true ? 1 : 0
console.log(operator)
# Answer
# 1
This Ternary operator is Similar in C programming language.

Hey mate just remember js works by evaluating to either true or false, right?
let's take a ternary operator :
questionAnswered ? "Awesome!" : "damn" ;
First, js checks whether questionAnswered is true or false.
if true ( ? ) you will get "Awesome!"
else ( : ) you will get "damn";
Hope this helps friend :)

It is called the ternary operator
tmp = (foo==1 ? true : false);

Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.
condition ? expressionIfTrue : expressionIfFalse
Think of expressionIfTrue as the OG if statement rendering true;
think of expressionIfFalse as the else statement.
Example:
var x = 1;
(x == 1) ? y=x : y=z;
this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.

x = 9
y = 8
unary
++x
--x
Binary
z = x + y
Ternary
2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";

It's an if statement all on one line.
So
var x=1;
(x == 1) ? y="true" : y="false";
alert(y);
The expression to be evaluated is in the ( )
If it matches true, execute the code after the ?
If it matches false, execute the code after the :

The conditional (ternary) operator is the only JavaScript operator
that takes three operands. This operator is frequently used as a
shortcut for the if statement.
condition ? expr1 : expr2
If condition is true, the operator returns the value of expr1;
otherwise, it returns the value of expr2.
function fact(n) {
if (n > 1) {
return n * fact(n-1);
} else {
return 1;
}
// we can replace the above code in a single line of code as below
//return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));
For more clarification please read MDN document link

This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.
// var firstName = 'John'; // Undefined
var lastName = 'Doe';
// if lastName or firstName is undefined, false, null or empty => fallback to empty string
lastName = lastName || '';
firstName = firstName || '';
var displayName = '';
// if lastName (or firstName) is undefined, false, null or empty
// displayName equals 'John' OR 'Doe'
// if lastName and firstName are not empty
// a space is inserted between the names
displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;
// if display name is undefined, false, null or empty => fallback to 'Unnamed'
displayName = displayName || 'Unnamed';
console.log(displayName);
Ternary Operator

We can use with Jquery as well as length as below example :
Suppose we have GuarantorName textbox which has value and want to get firstname and lastname- it may be null.
So rathar than
var gnamesplit = $("#txtGuarantorName").val().split(" ");
var gLastName = "";
var gFirstName = "";
if(gnamesplit.length > 0 ){
gLastName = gnamesplit[0];
}
if(gnamesplit.length > 1 ){
gFirstName = gnamesplit[1];
}
We can use below code with Jquery with minimum code
var gnamesplit = $("#txtGuarantorName").val().split(" ");
var gLastName = gnamesplit.length > 0 ? gnamesplit[0] : "";
var gFirstName = gnamesplit.length > 1 ? gnamesplit[1] : "";
$("#txtLastName").val(gLastName);
$("#txtFirstName").val(gFirstName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div >
Guarantor Name: <input type="text" id="txtGuarantorName" value="ASP.NET Core" /><br/>
<br/>
<br/>
First Name: <input type="text" id="txtLastName" value="ASP.NET Core" />
Last Name: <input type="text" id="txtFirstName" value="ASP.NET Core" />
</div>

Ternary operator is just a simple way to write if else condition. It is widely used in ReactJS.
For Example:
const x = 'foo';
// Instead of if else use this
x === 'foo' ? alert('True') : alert('False');
// Output
// alert box will prompt 'True'

It's called the ternary operator. For some more info, here's another question I answered regarding this:
How to write an IF else statement without 'else'

If you have one condition check instance function in javascript. it's easy to use ternary operator. which will only need one single line to implement.
Ex:
private module : string ='';
private page:boolean = false;
async mounted(){
if(this.module=== 'Main')
{
this.page = true;}
else{
this.page = false;
}
}
a function like this with one condition can be written as follow.
this.page = this.module=== 'Main' ?true:false;
condition ? if True : if False

By using Ternary operator, write a program to Print “Even Number”, if the number is even or Print “Odd Number”, if the number is odd.
let a = 13;
let b = a%2!==0 ? "is Odd number" : "is Even number";
// let b = a%2==0 ? "is Even number" : "is Odd number";
console.log(a+" "+b);
Output : 13 is Odd number

(sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";
sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"

Related

Expected expression, got keyword 'if' [duplicate]

What is the ?: (question mark and colon operator aka. conditional or "ternary") operator and how can I use it?
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.
I want to add some to the given answers.
In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.
Instead of:
var welcomeMessage = 'Hello ' + (username ? username : 'guest');
You can use:
var welcomeMessage = 'Hello ' + (username || 'guest');
This is Javascripts equivallent of PHP's shorthand ternary operator ?:
Or even:
var welcomeMessage = 'Hello ' + (username || something || maybethis || 'guest');
It evaluates the variable, and if it's false or unset, it goes on to the next.
It's called the 'ternary' or 'conditional' operator.
Example
The ?: operator can be used as a
shortcut for an if...else statement.
It is typically used as part of a
larger expression where an if...else
statement would be awkward. For
example:
var now = new Date();
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");
The example creates a string
containing "Good evening." if it is
after 6pm. The equivalent code using
an if...else statement would look as
follows:
var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
greeting += " evening.";
else
greeting += " day.";
From MSDN JS documentation.
Basically it's a shorthand conditional statement.
Also see:
Operator precedence with Javascript Ternary operator
Wikipedia
It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator".
If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $ symbol.
To answer your question, conditional operators replace simple if statements. An example is best:
var insurancePremium = age > 21 ? 100 : 200;
Instead of:
var insurancePremium;
if (age > 21) {
insurancePremium = 100;
} else {
insurancePremium = 200;
}
Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else :
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
Equivalent to:
function example() {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
More details is here
z = (x == y ? 1 : 2);
is equivalent to
if (x == y)
z = 1;
else
z = 2;
except, of course, it's shorter.
Ternary Operator
Commonly we have conditional statements in Javascript.
Example:
if (true) {
console.log(1)
}
else {
console.log(0)
}
# Answer
# 1
but it contain two or more lines and cannot assign to a variable.
Javascript have a solution for this Problem Ternary Operator.
Ternary Operator can write in one line and assign to a variable.
Example:
var operator = true ? 1 : 0
console.log(operator)
# Answer
# 1
This Ternary operator is Similar in C programming language.
Hey mate just remember js works by evaluating to either true or false, right?
let's take a ternary operator :
questionAnswered ? "Awesome!" : "damn" ;
First, js checks whether questionAnswered is true or false.
if true ( ? ) you will get "Awesome!"
else ( : ) you will get "damn";
Hope this helps friend :)
It is called the ternary operator
tmp = (foo==1 ? true : false);
Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.
condition ? expressionIfTrue : expressionIfFalse
Think of expressionIfTrue as the OG if statement rendering true;
think of expressionIfFalse as the else statement.
Example:
var x = 1;
(x == 1) ? y=x : y=z;
this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.
x = 9
y = 8
unary
++x
--x
Binary
z = x + y
Ternary
2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";
It's an if statement all on one line.
So
var x=1;
(x == 1) ? y="true" : y="false";
alert(y);
The expression to be evaluated is in the ( )
If it matches true, execute the code after the ?
If it matches false, execute the code after the :
The conditional (ternary) operator is the only JavaScript operator
that takes three operands. This operator is frequently used as a
shortcut for the if statement.
condition ? expr1 : expr2
If condition is true, the operator returns the value of expr1;
otherwise, it returns the value of expr2.
function fact(n) {
if (n > 1) {
return n * fact(n-1);
} else {
return 1;
}
// we can replace the above code in a single line of code as below
//return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));
For more clarification please read MDN document link
This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.
// var firstName = 'John'; // Undefined
var lastName = 'Doe';
// if lastName or firstName is undefined, false, null or empty => fallback to empty string
lastName = lastName || '';
firstName = firstName || '';
var displayName = '';
// if lastName (or firstName) is undefined, false, null or empty
// displayName equals 'John' OR 'Doe'
// if lastName and firstName are not empty
// a space is inserted between the names
displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;
// if display name is undefined, false, null or empty => fallback to 'Unnamed'
displayName = displayName || 'Unnamed';
console.log(displayName);
Ternary Operator
We can use with Jquery as well as length as below example :
Suppose we have GuarantorName textbox which has value and want to get firstname and lastname- it may be null.
So rathar than
var gnamesplit = $("#txtGuarantorName").val().split(" ");
var gLastName = "";
var gFirstName = "";
if(gnamesplit.length > 0 ){
gLastName = gnamesplit[0];
}
if(gnamesplit.length > 1 ){
gFirstName = gnamesplit[1];
}
We can use below code with Jquery with minimum code
var gnamesplit = $("#txtGuarantorName").val().split(" ");
var gLastName = gnamesplit.length > 0 ? gnamesplit[0] : "";
var gFirstName = gnamesplit.length > 1 ? gnamesplit[1] : "";
$("#txtLastName").val(gLastName);
$("#txtFirstName").val(gFirstName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div >
Guarantor Name: <input type="text" id="txtGuarantorName" value="ASP.NET Core" /><br/>
<br/>
<br/>
First Name: <input type="text" id="txtLastName" value="ASP.NET Core" />
Last Name: <input type="text" id="txtFirstName" value="ASP.NET Core" />
</div>
Ternary operator is just a simple way to write if else condition. It is widely used in ReactJS.
For Example:
const x = 'foo';
// Instead of if else use this
x === 'foo' ? alert('True') : alert('False');
// Output
// alert box will prompt 'True'
It's called the ternary operator. For some more info, here's another question I answered regarding this:
How to write an IF else statement without 'else'
If you have one condition check instance function in javascript. it's easy to use ternary operator. which will only need one single line to implement.
Ex:
private module : string ='';
private page:boolean = false;
async mounted(){
if(this.module=== 'Main')
{
this.page = true;}
else{
this.page = false;
}
}
a function like this with one condition can be written as follow.
this.page = this.module=== 'Main' ?true:false;
condition ? if True : if False
By using Ternary operator, write a program to Print “Even Number”, if the number is even or Print “Odd Number”, if the number is odd.
let a = 13;
let b = a%2!==0 ? "is Odd number" : "is Even number";
// let b = a%2==0 ? "is Even number" : "is Odd number";
console.log(a+" "+b);
Output : 13 is Odd number
(sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";
sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"

Using conditional operator to run more than one statement will not work

function isPrime(num) {
//TODO
let primeNum = false;
let prime = (num == 0 || num == 1) ? primeNum = false : (num == 2) ? console.log("2 is prime") :
(num % 2 == 0) ? console.log("num is divisable by 2 therefore is not prime") : {
console.log("number may be prime");
primeNum = true;
}
return primeNum;
}
Im attempting a challenge off of codewars to test if a num is prime. On my final conditional I want to print to console and set a value to primeNum. It seems to work fine if i do one or the other but not both.
I know its possible to do by writing a separate function containing both statements and having it be called instead or that I could use if and else statements but I'm trying to follow best practices here.
If you have to execute multiple things inside a single expression (such as inside one of the parts of the conditional operator), you may use the comma operator inside of parentheses. For example:
const condition = false;
const result = condition ? 'foo' : (
console.log('falsey!'),
'bar'
);
console.log(result);
Or, for your code:
function isPrime(num) {
const primeNum = (num == 0 || num == 1)
? false
: (
num == 2
? ( console.log("2 is prime"), true)
: (
num % 2 == 0
? (console.log("num is divisable by 2 therefore is not prime"), false)
: (console.log("number may be prime"), null)
)
);
return primeNum;
}
const result = isPrime(4);
console.log('4:', result)
But this is not a good idea - it's hard to read, and is not best practice. Better to use standard if/else statements instead.
Adding some brackets should to the trick, or your interpreter doesn't know what belongs to which expression.
Nested ternaries is not exactly best practices. Consider multiple if() return x;

Null and Booleans operator

I'm really new at programming and although I understand the concepts I have some trouble putting them in practice. For example I understood the concept of null and undefined values... and booleans operators.. all good!!! but when it comes to simple exercise I get stuck.
For example I got this :
Write an expression that evaluates x, so long as x is not null; if x is null, the expression should evaluate to 100. x is equal to null when no value has been assigned to it (e.g. var x;), but you could also assign it the value of null (var x = null;). Test your expression for several different values of x, including null - does it behave like you expect?
This is what I did:
var x ;
myExpression = (x - 50 + 20 + 30);
if (x === null) {
myExpression === true;
}
else if (x !== null) {
myExpression === 50;
}
It doesn't look right to me at all , and I know it's not. I think my real problem is understanding the problem itself. Can you please try to help me understanding it?
Thank you very much!
You are making this too hard. The expression:
((x == null) ? 100 : x)
A sample use:
y = ((x == null) ? 100 : x);
Your assignment said:
Write an expression that evaluates x, so long as x is not null; if x is null, the expression should evaluate to 100.
An expression is something which evaluates to a value. The number 6 is an expression. A variable, like x is an expression. More complicated expressions can be built using mathematical operators, for example 6 + x and so on.
The ternary (or "question mark") operator is a very powerful tool for building expressions.
condition ? value1 : value2
this works like something like a "mini-function":
function questionmark ( condition ) {
if ((condition) != 0) {
return value1;
} else {
return value2;
}
}
So:
(x == null) ? 100 : x
evaluates to 100 if x is null and the value of x otherwise.
Think of this expression as using 100 as the default value for something -- for example, we are going to do something x times, but if they haven't told us x we'll do it 100 times.
You should see that
(x != null) ? x : 100
is an equivalent expression.
In JavaScript there are more compact ("trickier") ways to write this kind of expression. I include them here just so you might recognize them if you see them in code:
(x ? x : 100)
(x || 100)

Condense this javascript using ternary operators

I am looking to assign rlPrice to either 0 (if undefined) or to the defined price which would be available. This below will do it ok.
if($('#rl option:selected').data("unit-price") == undefined){
rlPrice = 0;
else{
rlPrice = $('#rl option:selected').data("unit-price");
}
However is there a way to do it with ternary operators?
rlPrice = $('#rl option:selected').data("unit-price") OR 0;
Fastest way is to use coalescing operator:
rlPrice = $('#rl option:selected').data("unit-price") || 0;
See this link
The ternary operator has the form
d = a ? b : c;
Effectively, it means if a is true, then assign b to d, otherwise assign c to d.
So, replacing the real expressions in the above statement:
rlPrice = $('#rl option:selected').data("unit-price") == undefined?0:$('#rl option:selected').data("unit-price")
Your if..else statement is precised using the ?: opertor.
rlPrice = $('#rl option:selected').data("unit-price") == undefined
? 0
: $('#rl option:selected').data("unit-price");

How to write an inline IF statement in JavaScript?

How can I use an inline if statement in JavaScript? Is there an inline else statement too?
Something like this:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
You don't necessarily need jQuery. JavaScript alone will do this.
var a = 2;
var b = 3;
var c = ((a < b) ? 'minor' : 'major');
The c variable will be minor if the value is true, and major if the value is false.
This is known as a Conditional (ternary) Operator.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
There is a ternary operator, like this:
var c = (a < b) ? "a is less than b" : "a is not less than b";
For writing if statement inline, the code inside of it should only be one statement:
if ( a < b ) // code to be executed without curly braces;
You can also approximate an if/else using only Logical Operators.
(a && b) || c
The above is roughly the same as saying:
a ? b : c
And of course, roughly the same as:
if ( a ) { b } else { c }
I say roughly because there is one difference with this approach, in that you have to know that the value of b will evaluate as true, otherwise you will always get c. Bascially you have to realise that the part that would appear if () { here } is now part of the condition that you place if ( here ) { }.
The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator. Certain other languages, like PHP, carry on the actual result of the operation i.e. true or false, meaning the result is always true or false; e.g:
14 && 0 /// results as 0, not false
14 || 0 /// results as 14, not true
1 && 2 && 3 && 4 /// results as 4, not true
true && '' /// results as ''
{} || '0' /// results as {}
One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument i.e. as part of an assignment.
d = (a && b) || c;
d = a ? b : c;
if `a == true` then `d = b` else `d = c`
The only way to achieve this with a standard if statement would be to duplicate the assigment:
if ( a ) { d = b } else { d = c }
You may ask why use just Logical Operators instead of the Ternary Operator, for simple cases you probably wouldn't, unless you wanted to make sure a and b were both true. You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.
In plain English, the syntax explained:
if(condition){
do_something_if_condition_is_met;
}
else{
do_something_else_if_condition_is_not_met;
}
Can be written as:
condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;
If you just want an inline IF (without the ELSE), you can use the logical AND operator:
(a < b) && /*your code*/;
If you need an ELSE also, use the ternary operation that the other people suggested.
You could do like this in JavaScript:
a < b ? passed() : failed();
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>
parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
I often need to run more code per condition, by using: ( , , ) multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
FYI, you can compose conditional operators
var a = (truthy) ? 1 : (falsy) ? 2 : 3;
If your logic is sufficiently complex, then you might consider using an IIFE
var a = (function () {
if (truthy) return 1;
else if (falsy) return 2;
return 3;
})();
Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.
inline if:
(('hypothesis') ? 'truthy conclusion' : 'falsey conclusion')
truthy conclusion: statements executed when hypothesis is true
falsey conclusion: statements executed when hypothesis is false
your example:
var c = ((a < b) ? 'a<b statements' : '!(a<b) statements');
You can use the Ternary operator which equates to a simple if, else.
Ternary operation which calls functions for both outcomes:
(a < b) ? DoSomething() : DoSomethingElse();
Ternary operation which calls a function for only one of the outcomes:
(a < b) ? DoSomething() : {}; or (a < b)?.DoSomething();
To add to this you can also use inline if condition with && and || operators.
Like this
var a = 2;
var b = 0;
var c = (a > b || b == 0)? "do something" : "do something else";
Inline if in JavaScript is simple and requires no braces:
if (a < b) doSomething()
Technically you can have an else in the same line, but it requires a semicolon:
if (a < b) doSomething(); else doSomethingElse()
The above examples may not be desired by your team's coding standards. The most important thing is that you follow conventions that work for your team. Personally, I prefer if statements over ternaries in many cases because I find them easier to read.
Isn't the question essentially: can I write the following?
if (foo)
console.log(bar)
else
console.log(foo + bar)
the answer is, yes, the above will translate.
however, be wary of doing the following
if (foo)
if (bar)
console.log(foo)
else
console.log(bar)
else
console.log(foobar)
be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)
Simplify ternary operator
var locked = 1;
var canChange = locked != 1 ? true : false;
If the locked is 1, then the canChange variable is set to false, otherwise, it is set to true.
In this case, you can simplify it by using a Boolean expression as follows:
var locked = 1;
var canChange = locked != 1;
For multiple JavaScript ternary operators
The following example shows how to use two ternary operators in the same expression:
var speed = 90;
var message = speed >= 120 ? 'Too Fast' : (speed >= 80 ? 'Fast' : 'OK');
console.log(message);
It is a best practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you shouldn’t use the ternary operators.
(condition) ? expressionTrue : expressionFalse;
Example
int a=20, b=10;
if (a>b) {
cout << "a greater than b";
} else {
cout << "b greater than a";
}
You can simply write:
int a=20, b=10;
(a>b) ? cout << "a greater than b" : cout << "b greater than a";

Categories