Sam
Sam

Reputation: 1243

What is the javascript shorthand for this?

if(pf[i].length > highest){
    highest = pf[i].length;
}

What is the most efficient way of conveying the statement above?

Upvotes: 5

Views: 785

Answers (3)

Tushar
Tushar

Reputation: 87203

You can use Math.max to get the maximum of the two values, highest and pf[i].length.

highest = Math.max(highest, pf[i].length);

Or, you can also use ternary operator.

highest = pf[i].length > highest ? pf[i].length : highest;
//        ^^^^^^^^^^^^^^^^^^^^^^                          Condition
//                                 ^^^^^^^^^^^^           Execute when True
//                                                ^^^^^^^ Execute when False

The value from Ternary operation is returned and is set to the variable highest.

Upvotes: 4

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

Math.max function returns the largest of zero or more numbers.

highest = Math.max(pf[i].length, highest)

Upvotes: 7

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Try inline IF statement (ternary operator):

highest = pf[i].length > highest ? pf[i].length : highest;

Upvotes: 1

Related Questions