10

How to check isset in javascript.

I have used in the following way.

var sessionvalue = document.getElementById('sessionvalue').value;

if(Here I have to check if isset the sessionvalue or not){

  if(sessionvalue == "" || sessionvalue == null)
    {
        document.getElementById('sessionvalue').style.borderColor="red";
        return false;
    }
    else
    {
        document.getElementById('sessionvalue').style.borderColor="#ccc";
    }
}
1
  • similar but def not a duplicate question.. guy's asking about a variable, the referenced question is asking about array values. This is a good question. Commented Jul 3, 2019 at 5:11

5 Answers 5

20

When javascript variables are not declared and you try to call them, they return undefined, so you can do:

if (typeof sessionvalue == "undefined" || sessionvalue == null)

Sign up to request clarification or add additional context in comments.

1 Comment

@user3338098 The question was about if the object exists and not the object's property. Quite obviously, in order for the property of an object to exist, the object must exist first. So here your condition will slightly change. You will check if the object exists first and if it does, go on looking for the property. Refer an example here: jsfiddle.net/kx6gcLLm
16

You can just do:

if(sessionvalue)

The above will automatically check for undefined, null (And NaN ,false,"")

You can even make it a global function if you need it like you're used to in php.

function isset(_var){
     return !!_var; // converting to boolean.
}

1 Comment

awesome thank you! Can also check multiple vars like if ( (var1) && (var2) ) {}
2
    if(typeof(data.length) != 'undefined')
    {
       // do something
    }

    if(empty(data))
    {
        // do something
    }

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }

Comments

0

you can just do if(sessionvalue) that's it you don't need anything else and remember you can compare apples with cars in javascript, you can check if value is null or undefined with if(sessionvalue) or if(!sessionvalue), your code will be :

document.getElementById('sessionvalue').style.borderColor= sessionvalue ? "red" : "#CCC";

Comments

0

Try Code as below

var sessionvalue=document.getElementById('sessionvalue').value;
if(typeof sessionvalue != 'undefined'){

    if(sessionvalue=="" || sessionvalue == null)
    {
        document.getElementById('sessionvalue').style.borderColor="red";
        return false;
    }
    else
    {
        document.getElementById('sessionvalue').style.borderColor="#ccc";


    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.