Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "alert(a)'' and ''alert(a);var a =1;'' in javascript?

<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

like image 206
dukegod Avatar asked Jan 28 '16 06:01

dukegod


People also ask

What is the difference between alert and window alert in JavaScript?

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.

What is the meaning of JavaScript alert?

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.


1 Answers

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"

like image 166
gurvinder372 Avatar answered Sep 30 '22 16:09

gurvinder372