I think I'm a little confused of the nature of .length. Any help?

I want to check which word is the shortest, and I get the right answer when word2 or word3 is the shortest, but not word1. This also might be because I set the shortest as word1.length to begin with, but it may be because I’m returning numbers when I want to return values. Here’s my code:

function findShortestOfThreeWords(word1, word2, word3) {
    var newArr = [word1, word2, word3]
  var shortest = word1.length // shortest is the length of word1 (which is a number). I'm setting shortest to word1.length to start off with
  for (var i = 0; i < newArr.length; i++) { // loop over newArr
      if (newArr[i].length < shortest) { //if newArr[i]'s length (which is a number) is shorter than shortest
          shortest = newArr[i] // shortest now becomes newArr[i] (which is NOT a number)
      }
  }
  return shortest // return shortest
}
findShortestOfThreeWords('Hi', 'Hey', 'Hello')

Hello~!

.length returns a number - that number is the length of the string or object you’ve applied .length to.

In your function, you declare and initialise shortest as word1.length - so it starts out as a number. Let’s say… 5, for example purposes. Then, you loop through the array of words, checking the length of each. If that length value is less than shortest, you assign the word to shortest - now you’ve changed shortest from a number to a string.

In the end, you return shortest, which may either be a string or a number depending on whether your if statement runs.

There are two errors in your code:

  • If the shortest word is word1, you are returning the length.
  • If word2 is shorter than word1, but word3 is shorter than word2, you still return word2. This is because word2 gets assigned to shortest, and newArr[i].length < shortest cannot evaluate to true (as shortest is now a string.)

1 Like

Gothca’, I didn’t know about the second error in my code. How would you solve this? I’ve been stuck on this for a while

You need to ensure you are comparing the same types of value with every loop iteration.
If you’re going to compare newArr[i].length to shortest, then shortest should always be a number.
But if you want shortest to be a word, you can compare the lengths instead :slightly_smiling_face: