Omitting the second expression when using the if-else shorthand
Asked Answered
P

8

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.

Patent answered 17/6, 2012 at 6:0 Comment(20)
I think there's a var | var syntax. Careful as it's potentially difficult to "see", especially (IMO) ternaries being problematic. Use sparingly.Countermark
@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 .Rossie
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. :)Countermark
@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.Countermark
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.Propagable
@JaredFarrish: That's a || b or a && b, otherwise b will always be evaluated.Ellsworth
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.Countermark
@JaredFarrish Well I agree with you, but those specific cases do occur, and ternaries do help with readability in those cases.Rossie
@KennyTM - Oh ok, thanks. Is that an XOR?Countermark
@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.Countermark
@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.Propagable
@JaredFarrish true, you should only ever use code you are 100% you know what is doing.Propagable
@JaredFarrish: a != b or a ^ b. Both a and b will need to be evaluated, xor doesn't have short-circuiting.Ellsworth
@KennyTM - XOR gets my goat. I think the XOR wizard's been feeding it, too. Still a mystery what it does in practice logically.Countermark
@KennyTM - Also, is there a name for the construct of var a = b || c?Countermark
@JaredFarrish: I don't think there's a specific name, but see https://mcmap.net/q/75934/-javascript-operator and the related questions.Ellsworth
@KennyTM - Although it's not necessarily the "name" of the approach for this practice, I think "short-circuiting" is probably the best fit.Countermark
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.Cuprum
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.Cuprum
The correct answer to this question is the one by NickC https://mcmap.net/q/74952/-omitting-the-second-expression-when-using-the-if-else-shorthand Unfortunately it has not been marked as the correct answer.Leyes
T
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)

Tankard answered 17/6, 2012 at 6:33 Comment(9)
Oh, short-circuiting, right. Code readability is under appreciated I think in most intermediate developers and some "seasoned professionals".Countermark
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.Electrosurgery
I personally believe if it is a small if with one outcome if true.. its quicker and easier to write x == 2 && dosomething();Discobolus
if x==2 && doSomething() || doSomethingElse()Harty
yeah in minified version if loop changes into Short-circuiting.Forespent
This is terrible.Hidalgo
@KorayTugay Can you elaborate on what you think is terrible, or why?Whack
I wish JavaScript included this Ruby-like syntax: doSomething() if x === 2. I don't miss Ruby, but I do miss that.Ettore
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 assignmentFrication
A
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();
Avuncular answered 17/6, 2012 at 6:5 Comment(3)
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).Fibrinogen
you must use triple "=" signs for the logic to be perfect. as in var y = (x === 2 ? "yes" : "no");Childhood
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.Prinz
T
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)

Tankard answered 17/6, 2012 at 6:33 Comment(9)
Oh, short-circuiting, right. Code readability is under appreciated I think in most intermediate developers and some "seasoned professionals".Countermark
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.Electrosurgery
I personally believe if it is a small if with one outcome if true.. its quicker and easier to write x == 2 && dosomething();Discobolus
if x==2 && doSomething() || doSomethingElse()Harty
yeah in minified version if loop changes into Short-circuiting.Forespent
This is terrible.Hidalgo
@KorayTugay Can you elaborate on what you think is terrible, or why?Whack
I wish JavaScript included this Ruby-like syntax: doSomething() if x === 2. I don't miss Ruby, but I do miss that.Ettore
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 assignmentFrication
M
65

Another option:

x === 2 ? doSomething() : void 0;
Mellissamellitz answered 23/9, 2015 at 7:50 Comment(1)
If someone don't know why use void 0 i suggest read this linkLilalilac
F
23

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

if (x==2) doSomething();
Frameup answered 17/6, 2012 at 6:3 Comment(1)
you can do it even if you do the elseRiojas
C
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;
Curitiba answered 17/6, 2012 at 6:3 Comment(0)
C
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.. :)
Comma answered 4/11, 2015 at 11:26 Comment(0)
H
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).

Heavily answered 17/6, 2012 at 6:3 Comment(0)
J
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');
Jeffries answered 11/4, 2019 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.