<script type="text/javascript">
alert(a);
</script>
Console log shows : "Uncaught ReferenceError: a is not defined";
<script type="text/javascript">
alert(a);
var a = 1;
</script>
at the middle of the browse, Log shows: "undefined"
How does this code run in js and what causes this difference
Difference between alert() and window. alert() window in JS is a global object, that means you can access it anywhere throughout your code. So, alert() becomes a global method / function. Therefore, you can call alert function of window object as window.
The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to give a warning message to the users. It displays an alert dialog box that consists of some specified message (which is optional) and an OK button.
in this code
<script type="text/javascript">
alert(a);
var a = 1;
</script>
var a ;
is hoisted to the top and it becomes
<script type="text/javascript">
var a;
alert(a);
a = 1;
</script>
so by the time a
was alerted, it was undefined
In this code
<script type="text/javascript">
alert(a);
</script>
a was not defined at all, so it gave an error "Uncaught ReferenceError: a is not defined"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With