get_post_thumbnail_id()
is going to default to using the $post
global. That global is set to each post in turn as the Loop runs, so at the end of the Loop it will be set to the last post.
The easiest thing to do would be to set $image
before the Loop runs, but wp_reset_query
would do it too, if resetting the Loop does not through off other code on your page.
Also, you mention that you need this for Javascript. Javascript alone should be able to pick out the first URL in the markup that is already being printed by the Loop.