Javascript, string concatenation without ternary operator - javascript

Usually I use this:
myVar = "myString is" + 1 === 1 ? " really true" : " false, I think";
Maybe I need just the true part, let's say:
myVar = "myString is" + 1 === 1 ? " really true" : "";
I don't like this part: : "" because is useless.
Is there a way to use something like the below?
myVar = "myString is" + 1 === 1 && " really true";
It works but there is a problem when is false because it writes "false"!

You could always go with a good old if statement
var myVar = 'myString is';
if (1===1){myVar+=' really true';}
I think that makes it more readable than a one line boolean test

To be pragmatic the best pattern and best way to write this is to rely on a helper:
myVar = "my string is"+myHelper(...myParams);
Then in the helper we'll have a case/switch that is made exactly with this purpose and is really readable.

You can just use ||
myVar = (1 === 1 && "myString is really true") || "";

Wrap the 1 === 1 && " really true" inside parentheses () and add || '' like below (also wrapped in parentheses), or could use template literals to save you some time from typing those +s
let myString = "myString is" + ((1 === 1 && " really true") || '');
let myFalseString = "myString is" + ((1 === 0 && " really true") || '');
let onlyFalse = "myString is" + 1 === 1 && " really true";
let myTL = `myString is ${(1 === 1 && "really true") || ''}`;
console.log('My String:', myString);
console.log('False String:', myFalseString);
console.log('Only false:', onlyFalse);
console.log('My Template Literal:', myTL);
Looks much worse than having the extra : "" though so I would still recommend doing it like that:
myVar = "myString is" + 1 === 1 ? " really true" : "";

another way to achieve something like this could be to use an Array, and concat the values if they are not false. Not that it is any shorter than adding the : '', but as far as i know there is no way to get rid of the : ''
console.log( ["my string is", 1 === 1 && "really true"].filter(Boolean).join(" ") );
console.log( ["my string is", 1 === 2 && "really true"].filter(Boolean).join(" ") );
i would prob stick with the : '' or write a helper function that could look something like this.
function concat(){
let str = "";
for(let s of arguments){
str += s ? s : '';
}
return str;
}
console.log( concat("my string is", 1 === 1 && "really true") );
console.log( concat("my string is", 1 === 2 && "really true") );

Analysing the ternary operator we conclude that it's something like this:
// Example: 1 === 1 ? ' is really true' : ''
if (1 === 1) {
return ' is really true';
} else {
return '';
}
So the solution would be simply to remove the 'else' from the ternary operator, generating a 'binary'. Use a lone IF:
if (1 === 1) {
myVar += 'is really true';
}
The best solution to use the logic operator inline is the ternary operator itself. It's not a problem to have the 'false' part of it as a empty string "". But if you're really annoyed by it you could create a function and use the template literals like this:
function myFunction(evaluation) {
if (evaluation) {
return ' really true';
}
return '';
}
let myVar = `My String is ${myFunction(1 === 1)}`;

Related

Regex match() fails with 'is not a function' error [duplicate]

I’m using the match function with a Regular Expression.
The code I’m using is:
if(val.match(/^s+$/) || val == "" )
However, it produces the following error:
"val.match is not function"
What is the problem?
I would say that val is not a string.
I get the
val.match is not function
error for the following
var val=12;
if(val.match(/^s+$/) || val == ""){
document.write("success: " + val);
}
The error goes away if you explicitly convert to a string String(val)
var val=12;
if(String(val).match(/^s+$/) || val == ""){
document.write("success: " + val);
}
And if you do use a string you don't need to do the conversion
var val="sss";
if(val.match(/^s+$/) || val == ""){
document.write("success: " + val);
}
the problem is: val is not string
i can think of two options
1) convert to string: might be a good option if you are sure val has to be string
"Same as above answer"
var val=12;
if(String(val).match(/^s+$/) || val == ""){
document.write("success: " + val);
}
2) skip the line: in my case, it was better to just check the val type and skip if it is not string, because it was not a good idea to run "match" function anyways.
val = 12;
if( val.match) {
if(val.match(/^s+$/) || val == "" ) {
document.write("success: " + val);
}
} else {
document.write("not a string: " + val);
}
NOTE: making this an answer as suggested above from my comment.
Definitely make sure val is defined and a String. Also, I'm guessing it's a typo that you don't have a slash before the 's' in your regex. If that is the case you can replace your if test with "if(val.match(/^\s*$)"

Ternary Operator inside if statement? [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>"

I would like to understand the If shorthand in javascript applied [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>"

Can you define instructions, after .hasOwnProperty? [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>"

what does the '?' does in the return statement [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>"

Categories

Resources