My solution to "Find the Longest Word in a String". Opinions?

function findLongestWord(str) {
	var arr = str.split(' ');
	arr.sort(function(a,b) {
		return a.length < b.length;
  return arr[0].length;

findLongestWord("The quick brown fox jumped over the lazy dog");

This actually finds the length of the longest word and not the word itself.
You should be returning return arr[0]
However you can even be more efficient by using the Array.protoype.reduce() method


Oh alright. His post didn’t make it very clear. Thanks

function findLongestWord(str) {
  return str.split(' ').reduce(function(a, b) {
    if (a.length > b.length) {
      return a;
    } else {
      return b;

findLongestWord('The quick brown fox jumped over the lazy dog'); // 6

How do I improve my “code writing” to make it as neat as what youv’e wrote here? Its very hard for me to understand it.

codepen has option called tidy in javascript you may use it :slight_smile:

As @lkareeml said, you can use codepen’s tidy javascript to make your code cleaner (assuming you have correct syntax)
You can also use Markdown syntax to format javascript code on the freecodecamp forum.
You can see some cool Markdown helpers here: Markdown CheatSheet

1 Like