How to write an inline IF statement in JavaScript? - 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";

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

Does EcmaScript have "reverse if notation"?

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

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;

JavaScript Logical OR invalid assignment

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

What is the purpose of "condition && func()" when used as a statement?

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!

Categories