309

Can I write the if else shorthand without the else?

var x=1;

x==2 ? dosomething() : doNothingButContinueCode();   

I've noticed putting null for the else works (but I have no idea why or if that's a good idea).

Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Nikki
  • 3,664
  • 2
  • 15
  • 14
  • I think there's a `var | var` syntax. Careful as it's potentially difficult to "see", especially (IMO) ternaries being problematic. Use sparingly. – Jared Farrish Jun 17 '12 at 06:03
  • @JaredFarrish Isn't the whole point of ternaries that they're easier to "see" than using if statements? Also what is that syntax you're talking about, it looks interesting . –  Jun 17 '12 at 06:06
  • 1
    No, I don't think they're easier to at all in all cases. The "whole point" in my mind is to either put it all on one line ("my codes shorter than yours") or for specific, literal cases with simplistic outcomes. Stacking ternaries is particularly pernicious and should be avoided at all cost. `:)` – Jared Farrish Jun 17 '12 at 06:08
  • 2
    @Hassan - I've seen something like `foo = bar | cat;`, where if the first is false? null?, it "falls through" to the second. I've only seen it, though, and don't use it. – Jared Farrish Jun 17 '12 at 06:09
  • It's no problem doing something like this: var foo = bar || soap; where bar is a falsy value (remember, js has six different falsy values). This will make foo the value of soap. I use it often while creating "namespaces", where you never know if a value is set or not, like this. var ns = ns || {}; ns.something = {} // another namespace. – Robin Heggelund Hansen Jun 17 '12 at 06:10
  • 4
    @JaredFarrish: That's `a || b` or `a && b`, otherwise `b` will always be evaluated. – kennytm Jun 17 '12 at 06:11
  • Code is for the sake of the reader, so unless one approach has a significant impact on the codes execution over another approach for the same thing, brevity should not make an approach "best". I happen to think full `if` statements more readable/parse in a scan of the page. But I'm sure others disagree. – Jared Farrish Jun 17 '12 at 06:12
  • @JaredFarrish Well I agree with you, but those specific cases do occur, and ternaries do help with readability in those cases. –  Jun 17 '12 at 06:13
  • @KennyTM - Oh ok, thanks. Is that an `XOR`? – Jared Farrish Jun 17 '12 at 06:13
  • @RobinHeggelundHansen - Good points, I like that form in practice more than ternaries. I'm just prejudiced against ternaries I suppose. Too easy to let "clever" escape and with a little water and late night snacks you got a gremlin in your code. – Jared Farrish Jun 17 '12 at 06:15
  • @JaredFarrish I only ever use ternary operators to set a value, as it is less verbose than ifs. but for everything else (or if the ternary expression becomes to long and/or complex) i use the if construct as it's easier to read. – Robin Heggelund Hansen Jun 17 '12 at 06:16
  • @JaredFarrish true, you should only ever use code you are 100% you know what is doing. – Robin Heggelund Hansen Jun 17 '12 at 06:17
  • @JaredFarrish: `a != b` or `a ^ b`. Both *a* and *b* will need to be evaluated, xor doesn't have short-circuiting. – kennytm Jun 17 '12 at 06:20
  • @KennyTM - `XOR` gets my goat. I think the `XOR` wizard's been feeding it, too. Still a mystery what it does in practice logically. – Jared Farrish Jun 17 '12 at 06:23
  • @KennyTM - Also, **is** there a name for the construct of `var a = b || c`? – Jared Farrish Jun 17 '12 at 06:30
  • @JaredFarrish: I don't think there's a specific name, but see http://stackoverflow.com/questions/1378619/javascript-operator and the related questions. – kennytm Jun 17 '12 at 06:34
  • @KennyTM - Although it's not necessarily the "name" of the approach for this practice, I think "short-circuiting" is probably the best fit. – Jared Farrish Jun 17 '12 at 06:46
  • `condition && (codetorun)` they way it works is that && returns true only if both are true. So if condition is true, it goes to second which is in brackets so it computes that first, run it. then return true/false. But we are only concerned with act of running. So when it's condition is false, it just returns false as there is no need to evaluate 2nd statement as result will be false. – Muhammad Umer Aug 10 '13 at 13:07
  • `statement || statement` on the other side will run first one and then second. if first is false; so opposite of `&&`. `||` returns if only one is true, so if first statement is false, the second will be evaluated if in brackets then run, and returned. – Muhammad Umer Aug 10 '13 at 13:10
  • The correct answer to this question is the one by NickC http://stackoverflow.com/a/11069295/1044366 Unfortunately it has not been marked as the correct answer. – Sandeep Raju Prabhakar Jul 08 '14 at 07:48

8 Answers8

755

What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:

var y = (x == 2 ? "yes" : "no");

So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:

if (x==2) doSomething();
Nicole
  • 32,841
  • 11
  • 75
  • 101
  • In here we can add finishing line inserted as a full command (as my example use jquery fade in and fade out function) x == 2 ? $(element).fadeIn() :$(element).fadeIn() ; It not mandatory to have a return variable( like var y in first code). – Prageeth godage Jul 21 '14 at 17:15
  • 1
    you must use triple "=" signs for the logic to be perfect. as in var y = (x === 2 ? "yes" : "no"); – fino Dec 24 '14 at 21:11
  • Triple equal operator is only necessary when there may be type coercion between left and right arguments, and only if you don't actually intend to use type coercion. – Romain Vincent Sep 18 '21 at 12:50
296

This is also an option:

x==2 && dosomething();

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething();

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

ajax333221
  • 11,436
  • 16
  • 61
  • 95
  • 10
    Oh, short-circuiting, right. Code readability is under appreciated I think in most intermediate developers and some "seasoned professionals". – Jared Farrish Jun 17 '12 at 06:35
  • 2
    Technically you don't need the braces: `if (1 - 1 === 0) $('.woot').text('Woot!');` I use that form all the time with PHP, and now that I'm adopting Coffeescript, I use it in my Javascript as well. – b. e. hollenbeck Sep 14 '12 at 00:13
  • 5
    I personally believe if it is a small if with one outcome if true.. its quicker and easier to write x == 2 && dosomething(); – Dean Meehan Feb 18 '14 at 15:24
  • 9
    ```if x==2 && doSomething() || doSomethingElse()``` – Agustín Mar 31 '15 at 14:54
  • yeah in minified version `if loop` changes into Short-circuiting. – Mahi Nov 29 '16 at 07:20
  • This is terrible. – Koray Tugay May 25 '17 at 20:53
  • @KorayTugay Can you elaborate on what you think is terrible, or why? – Mark Jan 07 '18 at 13:30
  • 2
    I wish JavaScript included this Ruby-like syntax: `doSomething() if x === 2`. I don't miss Ruby, but I do miss that. – Chad Johnson Jul 26 '18 at 15:56
  • If instead of calling a function like `dosomething()`, what you need to do is set an assignment, you can't use a short-circuit. This works: `if(x==2) foo='bar'` But this: `x==2 && foo='bar'` gets an error: `Uncaught SyntaxError: Invalid left-hand side in assignment` – Bruno Bronosky Jan 02 '20 at 19:16
65

Another option:

x === 2 ? doSomething() : void 0;
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • 3
    If someone don't know why use void 0 i suggest read this [link](https://stackoverflow.com/questions/7452341/what-does-void-0-mean) – Carlinhos Jul 05 '17 at 19:50
23

If you're not doing the else, why not do:

if (x==2) doSomething();
Prescott
  • 7,312
  • 5
  • 49
  • 70
17

Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.

As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:

if (x==2) doSomething;
else doSomethingElse

or, in your case,

if (x==2) doSomething;
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
7

A small addition to this old thread..

If you're evaluating an expression inside a for/while loop with a ternary operator and want to continue or break as a result - you're going to have a problem because both continue & break aren't expressions; they're statements without any value.

This will produce Uncaught SyntaxError: Unexpected token continue

for (const item of myArray) {
    item.value ? break : continue;
}

If you really want a one-liner that returns a statement, you can use this instead:

for (const item of myArray) {
    if (item.value) break; else continue;
}
  • P.S - This code might raise some eyebrows. Just saying.. :)
Shaya
  • 2,792
  • 3
  • 26
  • 35
4

Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
3

Probably shortest (based on OR operator and its precedence)

x-2||dosomething()

let x=1, y=2;
let dosomething = console.log; 

x-2||dosomething('x do something');
y-2||dosomething('y do something');
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345