Reputation: 299
Why is the following line not alerted?
<script>
alert(x);//this line is not executed or alerted ???.It should have alerted "undefined"
console.log(x)//reference error
var y="maizere";
alert(y);//this line is also not executed or alerted ???
</script>
Any undeclared variables are treated as global variable in javascript right?
Upvotes: 0
Views: 322
Reputation: 19457
You are getting undefined
and undeclared
confused.
The variable x
is undeclared - it has not been declared in code yet, so
alert(x);
will raise an error in the likes of 'x' is not declared
.
Your code should read
<script>
var x;
alert(x);//this line is not executed or alerted ???.It should have alerted "undefined"
var y="maizere";
alert(y);//this line is also not executed or alerted ???
</script>
Upvotes: 2
Reputation: 72319
alert(x);//this line is not executed or alerted ???.It should have alerted "undefined"
That's incorrect. This line raises a ReferenceError
because there's no variable x
.
Contrast this with situation:
var obj = {};
alert(obj.x); // undefined - there's no attribute x
Upvotes: 2
Reputation: 2201
Whatever you put inside an alert
call should be defined. If it is not (your case) then an error is thrown. So, you should define the variable first. For the errors, you should check a JavaScript (browser) console.
var x = "Test";
alert(x); // shows
var y = 123;
alert(y); // y also shows, because there is no error thrown inside the alert for x
Upvotes: 0