I recently started diving into JavaScript programming. My current challenge involves creating a script that can identify and display the longest word in an array. Here's the code snippet I've come up with:
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 issue I'm facing is that the code consistently outputs the first element of the array as the supposed longest word (meaning longest = longWords[0]
). When I attempted to change longest = longWords[i]
to longest = longWords[i].length
, I ended up with the character count of the longest word instead of the actual word itself. Could you please enlighten me on why my initial approach didn't yield the desired result, and guide me on how I can achieve this task utilizing a for
loop?