Which is the best practise to write code in java script?

Which is the best practise to write code in javascript. Here i added java script in head tag(1st example) and body tag(2nd example) with example. If both are correct then what is the use of these two different method. Please throw some light on it.


<!DOCTYPE html>
<html>
<head></head>
<body>

<h1>Sample for Java-Script</h1>

<p id="para1">This is p tag</p>
<div id="div1">This is div</div>

<p>
<button type="button" onclick="func()">Click To Run</button>
</p>

<script>
function func() {
    document.getElementById("para1").innerHTML = "Hello There.";
    document.getElementById("div1").innerHTML = "How's Life?";
}
</script>

<p>When you click on "click to run", the two elements will change.</p>

</body>
</html>


<!DOCTYPE html>
<html>
<head>
<script>
function func() {
    document.getElementById("para1").innerHTML = "Hello There.";
    document.getElementById("div1").innerHTML = "How's Life?";
}
</script>
</head>

<body>

<h1>Sample for Java-Script</h1>

<p id="para1">This is p tag</p>
<div id="div1">This is div</div>

<p>
<button type="button" onclick="func()">Click To Run</button>
</p>

<p>When you click on "click to run", the two elements will change.</p>

</body>
</html>

Hi, welcome to the forums!

You almost always want to place any JS just before the closing </body> tag, to ensure that the page is loaded before any scripts are run.

Head section benefit: they get to run before the rest of the HTML content is processed. Realistically though there is no need for this now.
Head section downside: they delay the loading of the page, and result in a slower user experience.

Body section benefit: the HTML is already loaded so scripts can easily interact with the page, and people get to see the page load much sooner
Body section downside: Some positively ancient browsers that don’t understand HTML 4 can only load scripts from the head, such as IE4 and Netscape 4

Because the body section benefits are so great and the downside so minimal, loading scripts from the end of the body has become the preferred standard fro web development today.