0

I am currently working on a problem in coderbytes. I am supposed to create a function that takes in a string and returns the longest word in the string(no punctuation will be in the string and if there are two words the same size the function should return the first one). I was able to find a similar question Find the longest word/string in an array, but for some reason my code is not working.

var longestword = function(string){
    var longest = [];
    array = string.split(" ");
    for(var i = 0; i <= array.length; i++){
        if(array[i].length > longest.length){
        longest = array[i];    
        }
    }
console.log(longest)
}    
longestword("This isnt workin for some reason")

The error I am getting is TypeError: array[i] is undefined

2
  • It's javascript, the variable need not be declared. It's defined when it is assigned to on the third line. Commented Sep 9, 2014 at 4:26
  • 1
    The error you are speeking about is probably because you are using "<=" for the comparison in teh for() loop. Imagine your length is 9, your array will stop at 8 (because it begin at 0 not 1), use strict < not <= for the error. Commented Sep 9, 2014 at 4:27

2 Answers 2

4

Your condition is i <= array.length, but array indexes (for non-sparse arrays like this one) are 0 through array.length - 1. Just use <, not <=. You're getting undefined for array[i] when i is array.length because there's no element there.


Unrelated, but: Your code is falling prey to The Horror of Implicit Globals because you never declare array. Add a var in front of array = string.split(" ");

Sign up to request clarification or add additional context in comments.

Comments

0

You can't access array[array.length]. Arrays are 0-based. Change the <= to an <.

1 Comment

"You can't access array[array.length]" Well, you can (this is JavaScript!), but you'll get undefined. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.