jquery - Variable loses value on if statement in javascript -
jquery - Variable loses value on if statement in javascript -
i have simple html layout 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 reason when checking value of !user
using if condition, status successful , variable user
gets new value of 0
although defined previously. has been driving me crazy sometime now. there wrong above code?
you've redeclared "user" local variable in function. variable definitions in functions treated if occur @ start of function, meaning code equivalent to
$(document).ready(function () { var user; if(!user) { user = '0'; } alert(user); });
at if
statement, value of "user" undefined
. !user
test succeeds, , code proceeds set variable '0'
.
javascript jquery
Comments
Post a Comment