Your problem is with this line. arr[i] is undefined (a is just an empty array at this point) and you’re trying to access element 0 of undefined. You need to rethink your algorithm. Try using Math.max instead of trying to implement the max algorithm yourself, and the rest should be easy.
Good catch @InternetFriend, it’s sometimes hard to see missing braces.
@Mithil467: I recommend always using curly braces for loops and if statements. Leaving them out can cause bugs that trip up even experienced programmers.
Oh yes now it was accepted! Thank you very much! Thanks chuckadams for the other approach, thanks ieahleen and InternetFriend for the solution! I cannot mark both of your answers as solution though .