Vic
Vic

Reputation: 8981

Parentheses around string in JavaScript

I was reading Marionette's source code and I came across something like:

if (_.isObject(message)) {
    message = (
      message.prev + ' is going to be removed in the future. ' +
      'Please use ' + message.next + ' instead.' +
      (message.url ? ' See: ' + message.url : '')
    );
}

Why exactly is message wrapped in parentheses? What does that do?

Upvotes: 1

Views: 1684

Answers (3)

Cerbrus
Cerbrus

Reputation: 72857

In this specific example, the outer parentheses do not serve any function, other than (arguably) improving readability.

This code is functionally identical:

if (_.isObject(message)) {
    message = 
        message.prev + ' is going to be removed in the future. ' +
        'Please use ' + message.next + ' instead.' +
        (message.url ? ' See: ' + message.url : '');
}

The parentheses around the ternary operator are added so the ternary operator doesn't evaluate everything before the message.url.

Upvotes: 2

Zoltán Tamási
Zoltán Tamási

Reputation: 12764

I don't think the outer-most does anything. Probably the author used it for readability reasons. The inner is needed for the conditional (?) operator.

Upvotes: 1

taesu
taesu

Reputation: 4580

It's mainly for readability.
With or without, the functionality does not change.

Upvotes: 0

Related Questions