How to check 'undefined' value in jQuery
Asked Answered
C

12

197

Possible Duplicate:
Detecting an undefined object property in JavaScript
javascript undefined compare

How we can add a check for an undefined variable, like:

function A(val) {
  if (val == undefined) 
    // do this
  else
    // do this
}
Cold answered 18/5, 2012 at 13:16 Comment(1)
Possible duplicate of Detecting an undefined object propertyGenny
V
446

JQuery library was developed specifically to simplify and to unify certain JavaScript functionality.

However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:

if (typeof value === "undefined") {
    // ...
}

It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.

Vane answered 18/5, 2012 at 13:17 Comment(7)
@nahum jQuery is a JavaScript library. This is not a different programming language.Vane
lol omg are you really commenting this?? I know is the same man. But I guess he want to know if exist some kind of method in jQuery like $.isUndefined(Object); and return the value true or false. typeof is just javascript without any framework.Atahualpa
One of my problems was: if you are doing something like this ("#myId"), make sure what do you really need: a. typeof ("#myId")=== "undefined" b. Or: typeof ("#myId").val() === "undefined"Wilton
@Wilton ("#myId") is nothing else but a string constant. It will always be defined and have a type of "string". If you mean an actual jQuery object created with $("#myId"), it will always be defined as "object" (if you have jQuery linked correctly). Existence of a DOM element with ID myId can be assessed with if ($("#myId").length > 0) { ... }, while check if its value is not empty can be done with if ($("#myId").val()) { ... }. Neither of these clauses actually relate to the topic of this question.Vane
From jquery 1.4.2, you can use $.type(selector) === 'undefined' to check undefined value. Source: api.jquery.com/jQuery.typeEmunctory
it's supposed to be value === undefined without quotes. @Hast This works in jQueryGuevara
@user3284463 As mentioned in the answer, simple value === undefined will raise an exception if value variable does not exist. So it's completely up to you what to use in the real life.Vane
T
32

In this case you can use a === undefined comparison: if(val === undefined)

This works because val always exists (it's a function argument).

If you wanted to test an arbitrary variable that is not an argument, i.e. might not be defined at all, you'd have to use if(typeof val === 'undefined') to avoid an exception in case val didn't exist.

Tablespoon answered 18/5, 2012 at 13:24 Comment(0)
P
17

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

function A(val){
  if(typeof(val)  === "undefined") 
    //do this
  else
   //do this
}
Puri answered 18/5, 2012 at 13:18 Comment(2)
For string comparison, I think we need to use === instead of ==Chess
@Chess they both do comparison, just in different ways...this will work fineShrimp
E
12

I know I am late to answer the function but jquery have a in build function to do this

if(jQuery.type(val) === "undefined"){
    //Some code goes here
}

Refer jquery API document of jquery.type https://api.jquery.com/jQuery.type/ for the same.

Epiphyte answered 21/9, 2015 at 13:28 Comment(0)
C
5

You can use shorthand technique to check whether it is undefined or null

 function A(val)
 {
   if(val || "") 
   //do this
 else
 //do this
 }

hope this will help you

Carefree answered 3/6, 2015 at 10:41 Comment(0)
T
1

when I am testing "typeof obj === undefined", the alert(typeof obj) returning object, even though obj is undefined. Since obj is type of Object its returning Object, not undefined.

So after hours of testing I opted below technique.

if(document.getElementById(obj) !== null){
//do...
}else{
//do...
}

I am not sure why the first technique didn't work.But I get done my work using this.

Tonitonia answered 27/12, 2015 at 19:38 Comment(0)
E
0

If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0:

var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr'];
 jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) {
   var $_oField = jQuery("input[name='"+sShowKey+"']");
   if($_oField.val().trim().length === 0){
       $_oField.val('0.0')
    }
  })
Eogene answered 14/10, 2015 at 14:29 Comment(0)
L
0

I am not sure it is the best solution, but it works fine:

if($someObject['length']!=0){
    //do someting
}
Lorou answered 24/2, 2016 at 9:25 Comment(0)
I
0
function isValue(value, def, is_return) {
    if ( $.type(value) == 'null'
        || $.type(value) == 'undefined'
        || $.trim(value) == ''
        || ($.type(value) == 'number' && !$.isNumeric(value))
        || ($.type(value) == 'array' && value.length == 0)
        || ($.type(value) == 'object' && $.isEmptyObject(value)) ) {
        return ($.type(def) != 'undefined') ? def : false;
    } else {
        return ($.type(is_return) == 'boolean' && is_return === true ? value : true);
    }
}

try this~ all type checker

Inveigle answered 14/7, 2017 at 2:24 Comment(0)
S
0

Check if undefined or not

if(typeof myVal === "undefined") {
   //some code
}

Check if undefined or null or empty or false or 0

if(!myVal) {
   // some code
} else {
   // myVal is flawless 
}
Selfish answered 15/4, 2022 at 6:49 Comment(1)
What new this answer bring other than already said in other answers?Mesmerism
O
0

Try code about check ur code jQuery:

if (window.jQuery) { 
  console.log("Actived: jQuery");
} else {
  console.log("Disabled: jQuery");
}
Odalisque answered 24/11, 2023 at 15:55 Comment(0)
T
0
// Example variable
var myVariable;

// Using standard JavaScript methods
if (typeof myVariable === 'undefined') {
    console.log('myVariable is undefined');
}

// Using jQuery's utility function
if ($.type(myVariable) === 'undefined') {
    console.log('myVariable is undefined');
}
Trabue answered 19/2 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.