Reputation: 3920
I have this simple HTML layout as a test page:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
</script>
<script>var user = 'test';</script>
<script>
$(document).ready(function () {
if(!user) {
var user = '0';
}
alert(user);
});
</script>
</head>
</html>
For some reason when checking the value of !user
using the if condition, the condition is successful and the variable user
gets the new value of 0
although I defined it previously. This has been driving me crazy for sometime now. Is there something wrong with the above code?
Upvotes: 1
Views: 1727
Reputation: 21795
When DOM is loading variable 'user' is undefined. And in JavaScript (!undefined) is true, thus you are getting zero as output.
Upvotes: 1
Reputation: 413757
You've redeclared "user" as a local variable in the function. Variable definitions in functions are always treated as if they occur at the very start of the function, meaning your code is equivalent to
$(document).ready(function () {
var user;
if(!user) {
user = '0';
}
alert(user);
});
At the if
statement, the value of "user" will be undefined
. The !user
test succeeds, and so your code proceeds to set the variable to '0'
.
Upvotes: 4