How to write an inline IF statement in JavaScript?
Asked Answered
S

17

383

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
}
Senega answered 22/4, 2012 at 17:37 Comment(4)
Where's the jQuery here? And I don't really understand the question anyway.Yttriferous
jquery part might be like this $(document).ready(function(){ var a = 2; var b = 3; if(a < b) { // do something } });Senega
its a knockoutjs question tooBreath
It's also an angular 1 and 2 and every other js framework (including vanilla.js) out there questionHolloway
H
837

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

Hedron answered 22/4, 2012 at 17:40 Comment(8)
It illustrates how to use an Inline IF, which answers the question EXACTLY.Hedron
Just to note, all parens in this case are optional. It is often personal preference/coding style that dictates when they are used.Exegetics
@WillKlein you say all parens are optional yet when I do this as ()?: instead of (()?:) I get different results. I only know this because I tried it like it is in PHP.Gosnell
@khany, this is a JavaScript question. Expressions may evaluate in other languages differently.Exegetics
@Hedron This doesn't show how to use an Inline IF, it shows how to use an IF ELSEEnterprising
@Hedron is there a way to use the ternary if without else ?Sate
@Sate not really, but you could use a one line if statement if you wanted if (a < b) c = 'major';Hedron
Ah, yes, the null coalescing operator, and the joys of being multi-lingual.Deannedeans
B
63

There is a ternary operator, like this:

var c = (a < b) ? "a is less than b"  : "a is not less than b";
Berber answered 22/4, 2012 at 17:40 Comment(3)
It doesn't actually have to be assigned to anything. The right hand side elements can simply be function calls.Inertia
They don't even have to be function calls... 0 < 1 : 5 : 120; is a perfectly valid statement. A little useless unless you're paid per line, though.Tomtit
@Inertia I would advise against it in almost all cases, though. If you're not using the value of the expression, then what you really want is side effects; and side effects is what statements are great for. Using the plain old boring if statement in such a case will probably make your code much easier to read and understand, and less likely to break with later changes.Ravenna
A
57

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;
Andromede answered 22/4, 2012 at 17:43 Comment(0)
D
49

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.

Duumvir answered 4/11, 2013 at 10:2 Comment(0)
D
37

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;
Delmore answered 10/5, 2013 at 8:24 Comment(5)
Is it possible to do this without the "else" statement? ie condition ? trueReinforce
@ScottBeeson Sure. It also depends on your usage of the condition. true false and "" should all be fine to ignore the else portion.Delmore
So 2 == 2 ? doSomething() would be the same as if (2 == 2) doSomething()?Reinforce
Yes, but the else part cannot be completely omitted. At lease : false or : "" should be there as javascript is expecting this.Delmore
Oh. So it's not possible to do it without the else statement.Reinforce
F
27

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.

Filberto answered 14/7, 2015 at 3:51 Comment(0)
E
22

You could do like this in JavaScript:

a < b ? passed() : failed();
Etiquette answered 22/4, 2012 at 17:40 Comment(0)
P
22
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>

parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
Polemics answered 22/4, 2012 at 17:44 Comment(1)
I don't even know what I just read, but I'm laughing pretty hard.Ibnrushd
M
9

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 ) );
Meggs answered 31/8, 2017 at 8:15 Comment(0)
P
8

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.

Presently answered 1/8, 2016 at 20:58 Comment(0)
B
6

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');
Brelje answered 4/6, 2020 at 18:15 Comment(0)
B
5

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();
Bradleigh answered 4/3, 2022 at 11:54 Comment(0)
P
3

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";
Pheasant answered 10/10, 2013 at 6:37 Comment(0)
U
2

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.

Uniform answered 27/9, 2021 at 22:2 Comment(0)
F
1

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.)

Fining answered 16/7, 2015 at 14:42 Comment(0)
H
1

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.

Hyponasty answered 21/5, 2021 at 7:1 Comment(0)
A
0

Nobody's used arrays:

alert([prompt("falsey condition?"), prompt("truthy condition?")][BigInt(Boolean(2 == 1))]);
Aspirate answered 21/8, 2023 at 16:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.