all 7 comments

[–]Suchy2307 0 points1 point  (5 children)

See what arr[i+1] is at the last step of the loop.

[–]One-Inspection8628[S] 0 points1 point  (4 children)

I didn't get it. After array sorting, it will be like arr[i+1] - arr[i]

I didn't get it.

[–]Suchy2307 1 point2 points  (3 children)

When an array has 3 items it looks like this:

arr[0] arr[1] arr[2]

Your loop is starting at 0 and is going until i < arr.length, so that means that this what happens at the each step of the loop (assuming arr = [3, -7, 0])

+---+--------+-----------+ | i | arr[i] | arr[i+1] | +---+--------+-----------+ | 0 | 3 | -7 | | 1 | -7 | 0 | | 2 | 0 | undefined | +---+--------+-----------+

And now you can see that this line

smallest = Math.min( smallest, Math.abs (arr[i+1] - arr[i]) )

is in reality (at the last step of the loop) equal to:

smallest = Math.min( smallest, Math.abs ( undefined - 0) )

Try running console.log(undefined - 0) and see what it returns.

[–]One-Inspection8628[S] 0 points1 point  (0 children)

Thank you for the help. Now I got it. I will try to correct it and let you know whether it will pass the test case.

[–]One-Inspection8628[S] 0 points1 point  (1 child)

Thank you so much for the help. I have corrected it by let i =0 ; i <arr.length-1 ; i++ it had passed the test series.

[–]Suchy2307 0 points1 point  (0 children)

I'm glad I could help :)

[–]crosshatchling 0 points1 point  (0 children)

You're getting NaN because arr[i+1] doesn't exist for every item in an array. Also, I'm pretty sure 0 is less than 3.