2

What does this line of code do?

len = ( s.length>t.length ) ? s.length : t.length
rob mayoff
  • 342,380
  • 53
  • 730
  • 766
bubster
  • 847
  • 1
  • 10
  • 17

9 Answers9

7

?: is the ternary operator. It returns a value based on a condition.

x = (condition)?(if-true):(if-false)

So if condition is true, x is the value in the if-true section, and if it's false, then x is the value in if-false.

If is equivalent to what Corv1nus said earlier.

Dylan Lukes
  • 895
  • 7
  • 10
5

It's the equivalent of len = Math.max( s.length, t.length ); using the ternary conditional operator.

Victor Nicollet
  • 23,569
  • 3
  • 52
  • 88
4

It sets the variable len to the length of string s, or the length of string t, depending on which is longer.

Pekka
  • 418,526
  • 129
  • 929
  • 1,058
2

If s.length is greater than t.length set len = s.length else set len = t.length

jaywon
  • 7,818
  • 10
  • 36
  • 47
2

That is using the conditional operator, which is also known as a ternary because it takes three operands.

See https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Conditional_Operator for more info.

You can find this construct with the same syntax in PHP, C, C++ and other languages, too.

JAL
  • 20,237
  • 1
  • 45
  • 63
1

it is the equivalent of:

var len=0;
if(s.length>t.length)
  len= s.length;
else
  len=t.length;

So it's just a short way do doing if else.

albanx
  • 5,396
  • 8
  • 57
  • 89
  • Actually, the original didn't have `var`, so this isn't equivalent -- you're declaring a local variable, while the original may have been using a global. – Joe White Nov 12 '10 at 21:03
  • 1
    May have a global variable but may not have, it may be inside a function and global vars is not best practice programming so that's the best practice equivalent. – albanx Nov 16 '10 at 15:23
0

It is doing this:

if (s.length > t.length) {
    len = s.length;
} else {
    len = t.length;
}
Corv1nus
  • 4,143
  • 1
  • 24
  • 34
  • The original didn't have `var`, so this isn't equivalent -- you're declaring a local variable, while the original may have been using a global. – Joe White Nov 12 '10 at 21:04
0

len will be assigned the length of either s or t depending on which one has a greater length

Pete
  • 1,226
  • 1
  • 13
  • 33
0

If the length of s is greather than the length of t, make "len" the length of s. If the length of s is less than or equal to the length of t, make "len" the length of t.

Jake
  • 4,489
  • 2
  • 31
  • 44