Himmators
Himmators

Reputation: 15006

What's the reason to make a conditional without a result?

I came across this code:

navigation.on('click', '.main-nav-item', function (e) {
    var clickedNavItem = $j(this),
        className = clickedNavItem.data('class'),
        midNavItem = $j('.' + className, midNavigation);

    midNavItem.length > 0 && e.preventDefault();
});

I try to understand the purpose of the last row:

midNavItem.length > 0 && e.preventDefault();

It seems to stop the click if midNavItem.Length > 0, but I don't under stand the syntax of this. It ought to be_

if(midNavItem.length > 0) { e.preventDefault() };

Not two conditionals.

Why would you write it like this?

Upvotes: 2

Views: 50

Answers (2)

Shai
Shai

Reputation: 7317

How it works

It's known as short-circuit evaluation. You are correct – it is another way of writing the if statement you suggested:

if (midNavItem.length > 0) {
    e.preventDefault();
}

It works because && won't execute the second operand unless the first is truthy.

Why it is used

The rationale for using it is typically to make for neater code. This, of course, is subjective. There are probably people who say it is always better to explicitly use the if syntax – but you will also find a number of people / popular libraries using the shorthand extensively.

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

It's shorter.

Although in this case that "shortness" is lost by the large amounts of whitespace.

This is the kind of optimisation that should only be done by a minifying program, not manually, because it makes the code less readable.

Upvotes: 3

Related Questions