Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the javascript shorthand for this?

Tags:

javascript

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

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

like image 661
Sam Avatar asked Oct 16 '15 16:10

Sam


3 Answers

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

highest = Math.max(pf[i].length, highest)
like image 152
Manos Nikolaidis Avatar answered Oct 13 '22 00:10

Manos Nikolaidis


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.

like image 33
Tushar Avatar answered Oct 12 '22 22:10

Tushar


Try inline IF statement (ternary operator):

highest = pf[i].length > highest ? pf[i].length : highest;
like image 1
Zakaria Acharki Avatar answered Oct 13 '22 00:10

Zakaria Acharki