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>"
The normal way to write an if-statement is
if (a == b) {a=1}
but in eg. Perl it is possible to write the same as
a=1 if (a == b)
Question
Is a similar syntax possible with EcmaScript?
There is not a specific statement to do that. You still have several options though
if (a == b) {
a = 1
}
if (a == b) a = 1 // No parenthesis
a == b ? a = 1 : null // Using ternary operator
a = a == b ? 1 : a // Using ternary operator
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;
I'm trying to understand how JavaScript's logical OR operator works and I am trying to recreate a code I read in a book but with my own twist to it but I keep getting a reference error when I try to run the code.
function add(a,b) {
b || b = 1;
return a+b;
}
My understanding is that if the left operand is false then the right operand is evaluated then the right operand's value is returned or used. With the code above, what I am trying to do is when the function is invoked and the second parameter is omitted, it would use a default value of 1 as the second value to the equation, but I keep getting a reference error that states invalid left hand assignment.
Probably you wanna achieve this:
b = b || 1;
Try b || (b = 1) instead. That's also exactly what CoffeeScript generates for its ||= operator.
The problem is with operator precedence. Assignment = has lower precedence than boolean or ||, therefore this
b || b = 1
is interpreted as
(b || b) = 1
which is invalid, because you cannot assign to an expression. To achieve what you want you have to tell JS you want || first and then =:
b || (b = 1)
but a more common way to express this would be
b = b || 1
In the context of your function this might not work as expected, since 0 is a valid integer value, and your code will treat it as false and substitute it with 1. So, the correct, although more verbose, way to write your function is
function add(a, b) {
b = (typeof b == "undefined") ? 1 : b;
return a + b;
}
I recently ran across the following [effective] syntactical construct:
d <= f && func3();
The actual construct is of the form:
d > f ? a > b ? func1() : func2() : d <= f && func3();
What is the purpose of this construct?
My best guess is that func3 will only be executed if d <= f returns falsy because of the short-circuit evaluation in the && operator, but I don't think that makes sense given that the logic in the actual function would prevent d <= f from ever being false at that point in the code, and it's clear from DOM-watching that func3 is being executed.
If you want to see the whole code, I found this in http://cdn.sstatic.net/js/full.js?v=9358063bfb40 as referenced by https://stackoverflow.com/faq in the moveScroller function (full function below, it's in the line that has d <= f && j.css({...}) to reset back to a relative position).
function moveScroller() {
var g = $("#scroller").width(),
d = function () {
var d = $(window).scrollTop(),
f = $("#scroller-anchor").offset().top,
j = $("#scroller");
d > f ? j.height() > $(window).height() ? j.css({
position: "fixed",
top: "",
bottom: "0px",
width: g
}) : j.css({
position: "fixed",
top: "0px",
bottom: "",
width: g
}) : d <= f && j.css({
position: "relative",
top: "",
bottom: ""
})
};
$(window).scroll(d).resize(d);
d()
}
As you surmised, it means almost the same thing as
if (var1 <= var2) someFunction();
It doesn't mean exactly the same thing; the if statement is, well, a statement, while that && construct is just an expression (and so might be part of a larger expression).
edit — I do agree now that because that code is in the "else" wing of the ?: operator that "d" has to be less than or equal to "f". Perhaps it was written that way to clarify things, but I have the feeling that the author of that code wan't much interested in clarity.
It's basically hacking the boolean && operator. People sometimes use && and || operators as shortcuts for conditions. This is possible, because of the behaviour of these operators:
&& will check second operand only when first operand is true, e.g. true && thisWillAlwaysBeExecuted() and false && thisWillNeverBeExecuted
|| operator will check second operand only when first operand is false, e.g. true || thisWillNeverBeExecuted() and false || thisWillAlwaysBeExecuted()
I think it's a bad practice because it hides the intent. What that expression means is: "compare these two operands" and the intent is "if certain condition is met - perform this task". I really doubt that there's any gain in performance, and the argument "it's less characters" stopped working when the first IDE was invented.
d > f ? a > b ? func1() : func2() : d <= f && func3();
Is d more than f? If true then
a > b ? func1() : func2()
Is a > b? If true then run func1(). If not true then run func2().
If d was not more than f, then
d <= f && func3();
if d is less than or equal to f, run func3()
Edit
As to the purpose of using the && it is usually done when you want to avoid doing the later part of the conditional statement, and essentially break, if the condition prior to the && was false. Usually these are used to make sure that a property which does not exist is not accessed by testing for it or for a feature which guarantees its existence.
If either d or f are non-numeric (NaN, non-number strings, etc) then both tests d > f and d <= f can return false.
So in the code
d > f ? a > b ? func1() : func2() : d <= f && func3();
at first glance it looks like d <= f is redundant, but it will short-circuit the execution of func3 if either d or f is non-numeric.
Ugly code!