9

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";
    }
}
Arulkumar
  • 12,966
  • 14
  • 47
  • 68
dhiv
  • 121
  • 1
  • 1
  • 6
  • 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. – Robert Sinclair Jul 03 '19 at 05:11

5 Answers5

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)

AyB
  • 11,609
  • 4
  • 32
  • 47
  • @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: https://jsfiddle.net/kx6gcLLm/ – AyB May 11 '16 at 05:35
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.
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
2
    if(typeof(data.length) != 'undefined')
    {
       // do something
    }

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

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }
Naresh
  • 2,761
  • 10
  • 45
  • 78
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";
Labib Ismaiel
  • 1,240
  • 2
  • 11
  • 21
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";


    }
}
Gopal Joshi
  • 2,350
  • 22
  • 49