David Liao
David Liao

Reputation: 231

Conditional function call without if

I used the following code a lot in my work

if (people === 'someone') {
  doSomething();
}

Is there any shorter way to do it ?

Upvotes: 1

Views: 12822

Answers (2)

Ravi Mule
Ravi Mule

Reputation: 404

You can use ternary operator. A Standard Ternary is simple, easy to read, and would look like this:

$value = ($people === 'someone') ? doSomething() : 'nothing';

or

echo ($people === 'someone') ? doSomething() : 'nothing';

Upvotes: -2

Quan Lieu
Quan Lieu

Reputation: 307

You can write like this:

people === 'someone' && doSomething()

It means if the left side is true, then right side will be take into action. If the left side is false, the statement end.

Note: I agree with meagar , if is more readable.

And in case you interested in how the logic operator work, see this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

Upvotes: 9

Related Questions