Var outside of Function Meaning

I’ve seen a lot of excercises with a var outside that is used inside the function. Here’s a code segment:

function getLongestOfThreeWords(word1, word2, word3) {
  var words = [word1, word2, word3]
  
  var longest = words[0]
  for (var i = 1; i < words.length; i++) {
if (words[i].length > longest.length) {
    longest = words[i];
}
}
return longest
}

I’m not sure what that var longest is doing and that we redefine it again (longest = words[i]). Can someone clarify please?

In var longest = words[0] variable longest is declared and it has assigned words[0]. You can think about this assignment as kind of base case. First word (with index 0) is assigned as the longest, because there weren’t any other words checked before.

Later in the loop length of the next word is compared to the currently longest word and if it’s longer longest = words[i] assigns to the longest variable that word.

// Return the longest of three input words
function getLongestOfThreeWords(word1, word2, word3) {
  // Put words in array for convenience
  let words = [word1, word2, word3];
  
  // Initial guess for longest word
  let longest = words[0];

  // Check rest of array for longer word
  for (let i = 1; i < words.length; i++) {
    // Update longest if longer word fourd
    if (words[i].length > longest.length) {
      longest = words[i];
    }
  }

  // Return longest word
  return longest;
}

I indented your code to make it easier to read and understand. I also added some comments. Comments are a good thing to add to help you remember how your code works.

Now, I am going to critique your choice of words a little bit. The variable longest was not declared outside of your function. It was declared outside of the for loop inside of your function.

With these comments we can now see what the purpose of longest is. This variable holds the longest word we have found so far, and we update it every time we find a longer word.

I recommend that you write comments describing what your code needs to do before you write your code! This helps you think about the process for solving the problem rather than getting overly excited about putting in code and making things happen. It also helps you understand what you wrote when you come back to this code in the future.

I hope this helped, but please ask questions if I can be clearer!

1 Like