-1

I am trying to get JS to get the word with the most characters but for some reason my code always returns "The"

I have tried two variants of the code.

Variant 1:

let sent = "The quick borwn fox jumped over the jazy dog";
let word = findWord(sent);

function findWord(sent){

  splitSent=sent.split(" ");

  let largest="";

  for(i=0; i<splitSent.length;i++){

    if(splitSent[i].length>largest){

        largest=splitSent[i];
    }

  }

return largest;
}

console.log(word)

Variant 2:

let sent = "The quick borwn fox jumped over the jazy dog";
let word = findWord(sent);

function findWord(sent){

  splitSent=sent.split(" ");

  let largest="";

  for(split of splitSent){

    if(splitSent[i].length>largest){

        largest=splitSent[i];
    }

  }

return largest;

}

console.log(word)

the console just prints "The" from the first code and "fox" from the second

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • `largest` is a string, so `splitSent[i].length>largest` doesn't make sense, try comparing against `largest.length` instead. You should also consider avoiding implicitly creating global variables – CertainPerformance Jun 10 '19 at 01:09

1 Answers1

1

Because you need to check largest.length not largest.

let sent = "The quick borwn fox jumped over the jazy dog";    
let word = findWord(sent);

    
function findWord(sent) {      
  splitSent = sent.split(" ");      
  let largest = "";      
  for (i = 0; i < splitSent.length; i++) {        
    if (splitSent[i].length > largest.length) {          
      largest = splitSent[i];        
    }      
  }      
  return largest;    
}

    
console.log(word);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79