why is simple javascript code not running?

why is simple javascript code not running ?

<script type="text/javascript" charset="utf-8">

var btn = document.getElementById("myBtn");
btn.onclick = function(){
alert("Clicked");
};

</script>

<a id="myBtn" href="#">click me </a>


Assign your onclick handler after document is loaded.

<script type="text/javascript" charset="utf-8">

function assignHandler() {
    var btn = document.getElementById("myBtn");
    btn.onclick = function() {
        alert("Clicked");
    };
}

</script>

<body onload="assignHandler()">
<a id="myBtn" href="#">click me </a>
</body>