when we need to add some javascript code to html, where we have to put it?
Optimally, it's loaded just before the body tag closes

    &lt;!-- all html above here --&gt;
    &lt;script src="..."&gt;&lt;/script&gt;
&lt;/body&gt;


for the following common reasons:


The DOM elements that you are operating are safely parsed by then.
Script tags block execution. If they delay in loading and/or parsing, the things that follow it will have to wait. Thus, to prevent delay and from seeing a blank screen while scripts load, we load the page first, scripts last.


I have a similar answer, along with other answers, at StackOverflow which should explain more.