admin管理员组

文章数量:1393843

<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

<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

Share Improve this question edited Jan 28, 2016 at 6:51 stark 2,2562 gold badges24 silver badges35 bronze badges asked Jan 28, 2016 at 6:43 huihui 6018 silver badges22 bronze badges 3
  • 7 Variable hoisting – Tushar Commented Jan 28, 2016 at 6:44
  • in second case var a = 1; if you will declare variable after alert undefined error will occurs – Gautam Jha Commented Jan 28, 2016 at 6:49
  • there is a typo it should be alert(a) not alter(a) – brk Commented Jan 28, 2016 at 6:49
Add a ment  | 

1 Answer 1

Reset to default 7

in this code

<script type="text/javascript">
    alert(a);
    var a = 1;
</script>

var a ; is hoisted to the top and it bees

<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"

本文标签: htmlDifference between quotalert(a)3939 and 3939alert(a)var a 13939 in javascriptStack Overflow