Condense this javascript using ternary operators - javascript

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");

Related

Ternary operator within parentheses -- What does this do? [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>"

Assign 0 if the value is null or empty in Jquery

I want to use a ternary operator for the below jQuery statement like if employee_salary is empty or null, I want to assign as 0 (zero). Otherwise, just assign the actual value.
jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']))
var employee_salary = selected_table_data['employee_salary'];
var salary_form_value = employeeSalary ? parseInt(employee_salary) : '0';
jQuery('#employee_form #employee_salary').val(salary_form_value);
// If you want to inline it, you could do the following:
jQuery('#employee_form #employee_salary').val(
selected_table_data['employee_salary']
? parseInt(selected_table_data['employee_salary']
: 0
);
Here is an example
const s1 = null;
console.log(s1 ? s1 : 'There was a null value');
const s2 = ''
console.log(s2 ? s2 : 'There was an empty string');
const s3 = 'value';
console.log(s3 ? s3 : 'There was no value');
You can use ternary operator simply.
selected_table_data['employee_salary']
? parseInt(selected_table_data['employee_salary'])
: 0
console.log('' || 0);
console.log(null || 0);
console.log(undefined || 0);
I suspect that parseInt was your attempt to make this work yourself (fair enough). I'm going to suggest you remove it and try simply
jQuery('#employee_form #employee_salary').val(selected_table_data['employee_salary'] || 0);
A simple solution for you.
jQuery('#employee_form #employee_salary').val(selected_table_data['employee_salary'] * 1)
Using || operator or just a simple ternary operator would work if its null, undefined or ''. But it won't work for a blank space like this one ' ' (since Boolean (' ') evaluates as true) which it's not good if you want to replace any empty string or blank spaces for zero. So I would suggest you to do something like this,
jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']) ? parseInt(selected_table_data['employee_salary']) : 0);
This will allow you not only check if null, undefined, empty string and white spaces but also will prevent NaN to be a value on your form (instead zero will take place).

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>"

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";

What is this JS syntax? Assignment in expression? (x != null && (y = x))

I'm working with this JS plugin, and I've encountered some syntax I've never seen before. I understand what it's doing, but I'm not sure why it works.
Here's an example of one instance of it:
settings.maxId != null && (params.max_id = settings.maxId);
Is this just taking advantage of conditionals and the single = ? Is this common syntax for JS?
In JavaScript the = operator is an expression and evaluates the assigned value. Because it is an expression it can be used anywhere an expression is allowed even though it causes a side-effect.
Thus:
settings.maxId != null && (params.max_id = settings.maxId)
Means: If settings.maxId is not null then (and only then, since && is short circuiting) evaluate the right-expression (params.max_id = settings.maxId) which in turn causes the value of settings.maxId to be assigned to params.max_id.
This is much more clearly written as:
if (settings.maxId != null) {
params.max_id = settings.maxId
}
Happy coding.
The && operator is known as "boolean AND". Typically, you'd see it in an if statement:
if (x == true && y == false) {
but that's not a restriction. You may use it in any valid expression to "combine" the boolean values of its operands into a single boolean result, according to the logical "AND" operation:
var z = (x == true && y == false);
// z is now true or false, accordingly
One of the lovely things about && is that it "short circuits". In false && true, because the first operand is false the entire expression may only evaluate to false, so the second operand is not even evaluated.
Let's check that again:
var z = (false && foo());
// z is now false
In this statement, the function foo is never even called! It doesn't have to be, for the program to know that z will be false.
This is more than an optimisation — you can rely on it.
Some silly people use this technique to rewrite conditional statements:
if (x == 0) {
foo();
}
into hard-to-read single expressions:
(x == 0) && foo();
Now, consider that assignment can be an expression just like a function call:
var a = (b = c);
Or:
var a = (b = foo());
And add in a conditional via the above technique:
var a = ((x == 0) && (b = foo()));
Now the entire expression b = foo() won't be evaluated at all if x is not 0, because of short circuiting.
We don't even need to do anything with the result of the && operation, and if we don't store it to a you're left with just:
(x == 0) && (b = foo());
which is a statement that'll assign b to the value of foo() only if x is 0.
Avoid it. It's hard to read. Just use an if statement.
this statement will assign params.max_id = settings.maxId only if settings.maxId != null due to the fact that && is a short-circuit logic operator
this behaviour is due to the fact that javascript will evaluate the condition until it's necessary. thus, if first condition is false and the second is in AND there's no need to check further

Categories