9

Are the two identical?

Suppose you have:

var x = true;

And then you have one of either:

x && doSomething();

or

if(x) doSomething();

Is there any differene whatsoever between the two syntaxes? Did I stumble across a nice bit of sugar?

3
  • In your case result will be same. Commented Sep 30, 2012 at 19:21
  • 1
    Do you minify your code? If so, don't do this. Write clear, readable code, and let the minifier take care of the tweaks. Commented Sep 30, 2012 at 19:50
  • @user1689607 I personally find the former more concise/elegant/readable, assuming that its semantically identical. Commented Oct 3, 2012 at 2:29

5 Answers 5

7

Strictly speaking, they will produce the same results, but if you use the former case as a condition for something else, you will get dissimilar results. This is because in the case of x && doSomething(), doSomething() will return a value to signify its success.

Sign up to request clarification or add additional context in comments.

3 Comments

can I use the syntax for other types of statements? They're all expressions anyway, aren't they? I mean, var x; <boolean expr> && x = 'boolean expr was true';. Can any statement that would follow an if(condition) follow the && to produce the same result, even if it doesn't involve a method call?
Any expression that evaluates to a value can be included in a boolean operation.
aren't all statements in js expressions, though?
6

No, they are not identical. While if is a statement, the AND operator is an expression.

That means you could use its result in an other expression, which you can't with an if-statement:

var result = x && doSomething();

Yet, in your case both have the same effect. Use the one that is more readable and represents your program structure better; I'd recommend the if-statement.

3 Comments

@AdrienBe: What should these links tell me?
Some further reading for people interested in finding out more about javascript statement and expression you mentioned in your answer, ie. differences, keywords, and so on
3

Short answer: No.

Long answer:

A stated by @Steve x && doSomething() is an expression,

whereas if(x) doSomething(); is a statement,

As suggested by @Daniel Li and @Bergi, think:

  • an expression is computed ( supposed to return a value here ).

  • a statement is declared ( not supposed to return a value here, think side-effects ).

Why is it confusing?

  • JS allows us to write ( thatExpression );
  • JS allows us to write thatExpression;

both assuming some kind of doNothingWithValueOf statement.

How to choose?

Do you use:

  • doSomething() as an
    • expression , think IsMyObjectWhatever() or MyObjectComputedValue(),
    • or as a statement, think ModifyMyObject()

And then: Do you use x && doSomething() as an expression ?

You'll end up thinking something like thisStatement( thatExpression ); everywhere, think:

  • () expression,
  • ; statement.

Then why should I choose?

Comments

1

In a word no, the two statements are not equal, though in the specific circumstances you present the outcome is the same.

x && doSomething(); is an expression, first the x evaluated, because this is an AND and since x is true the second argument (doSomething()) is then evaluated. In this case this means that the method is executed. If x were false then doSomething() would not be executed as the result of the expression cannot be true.

if(x) doSomething(); is a statement. The value of x is checked, and if it is true the scope of the if statement is executed.

I've put together this fiddle to demonstrate (with minor modifications).

1 Comment

Are all expressions valid as freestanding statements?
0

Let's play detective.

We'll call our first approach Conditional Arrow Invocation and our second approach Traditional If Else.

We'll create two separate cases in jsperf to evaluate how these two approaches fair.

Conditional Arrow Invocations

const VALUE = true;
const TEST = false;

//test 1
VALUE && !TEST && (() => {
    console.log('print me!');
})();

Ops/sec result:

  1. FireFox: 65,152
  2. Chrome: 129,045

Traditional If Else

const VALUE = true;
const TEST = false;

//test 2
if(VALUE && !TEST) {
    console.log('print me!');
}

Ops/sec result:

  1. FireFox: 65,967
  2. Chrome: 130,499

Conclusion

As you can see, performance wise there isn't a huge difference but marginally Traditional If Else won over Conditional Arrow Invocation most of the times by an insignificantly small number. This might have something to do with creating an implicit function on the fly.

I also realized Chrome's JavaScript is a lot faster than FireFox's JavaScript execution.

Here is the jsperf link that you can run to evaluate this for yourself.

https://jsperf.com/conditional-methods-vs-traditional-if-else/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.