I just started learning JavaScript. I am trying to write a JavaScript to find and print the longest word in an Array. I came up with the code below:
var longWords = ["Penelope", "Johny", "Aubumayang", "Czechoslovakia", "Slovenia"]
var longest = 0;
for (var i = 0; i < longWords.length; i++) {
if (longest < longWords[i].length) {
longest = longWords[i];
}
}
console.log(longest)
The problem is it always end up printing the first element in the array. which means longest = longWords[0]
. Now when I change the line longest = longWords[i]
to longest = longWords[i].length
I get the count of the longest character. Please tell me why it didn't work and how I can do this using the for
loop.