Martin C
Martin C

Reputation: 395

Difference between both variable declaration

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

Answers (1)

Dagg Nabbit
Dagg Nabbit

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

Related Questions