Need an explanation

Hello everyone, so I’m asking if anyone could help me understand this function. I was reading on MDN about the arguments object and I came across this segment of code in one of the examples that they were giving. And this function, as they explained, accepts any number of string arguments and returns the longest one. What I can’t seem to understand that if we pass any number of string in the function wouldn’t all their lengths be greater than zero. Also wouldn’t the variable longest contain all their values. I mean that’s my understanding at the moment and I know that I’m missing something or that I’m wrong.
Anyways, I’d really appreciate any help that you’ll give me. And sorry for my English if I couldn’t explain this the right way.

function longestString() {
  var longest = '';
  for (var i=0; i < arguments.length; i++) {
    if (arguments[i].length > longest.length) {
      longest = arguments[i];
    }
  }
  return longest;
}

Yes. That doesn’t cause any problems.

Nope. The variable longest gets reassigned when a longer string is found. It doesn’t combine the two strings.

1 Like

Oh, so it gets reassigned as it detects a greater value. I didn’t know that. Thank you for letting me understand.

I’m glad I could help. Happy coding!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.