Reputation: 395
I am using a simple code to check if session variable is not set then page redirect to another page usign javascript. My code is:
var userLogin = "<?php echo $_SESSION['user']['id']; ?>";
if (typeof userLogin == "undefined")
{
$(location).attr('href', 'http://www.example.com/');
}
But it's not working because if session is not set then it assign:
var userLogin = "";
My question is: What is difference between both variable declaration:
var userLogin = "";
and
var userLogin;
Upvotes: 0
Views: 85
Reputation: 76766
The difference is that var userLogin
assigns a value of undefined
to userLogin
, while var userLogin = ""
assigns an empty string as its value.
Use if (!userLogin)
instead of if (typeof userLogin == "undefined")
.
When writing an expression
if (x) { ... }
JavaScript considers the following x
values to be false
undefined
, null
, NaN
, 0
, ""
(empty string), and false
All other values for x
are considered true
Upvotes: 5