How to check for null or undefined methods? - javascript

Somewhere along the line jQuery changed it's handling of non-existent elements. Assume #nearby element does not exist, then
console.log($('#nearby').html());
A) In jQuery <= 1.7.2, it prints out null
B) In jQuery > 1.7.2, it prints out undefined
I am trying to support checking for both cases. The following works:
if ($('#nearby').html() === null || $('#nearby').html() === undefined)
{
console.log('nothing here');
}
Is there a less ugly way of checking for null or undefined methods? I tried a boolean check:
(`if ($('#nearby').html()))` ...
But it didn't work. So, Is there a better way?
Note that this is not a check for undefined/null variables, for which there are a million answers on SO.

If you want to check if an element exists, why not use:
If (!$('#nearby').length)
{
console.log("nothing here...")
}
console.log(!$('#nearby').length);
if (!$('#nearby').length)
console.log("#nearby do not exists!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In the other hand, if the element exists and you want to check if some method is available for that element, then you can use typeof
if ($('#nearby').length && typeof($('#nearby').html) !== "function")
console.log("html() is undefined!");
if ($('#nearby').length && !typeof($('#nearby').foo) !== "function")
console.log("foo() is undefined!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="nearby"></div>
So, in summary, if you want to check if the element don't exists or some method isn't available to use on it, you can do this.
if (!$('#nearby').length || typeof($('#nearby').foo) !== "function")
console.log("Nothing here...")

if (!$('#nearby').html() || $('#nearby').html() == null ||
$('#nearby').html() == 'undefined') {
console.log('nothing here');
}
that works for me

You can check for both cases using :
if (!!$('#nearby').html()) {
console.log('nothing here');
}
because undefined or null are both false.

Related

When checking for undefined value, I keep getting errors because the value is undefined. How do I properly check for undefined values?

The code is as follows:
if(typeof state.getId().stateId !== "undefined") {
console.log("Not undefined");
} else {
console.log("Undefined");
}
I keep getting this error:
TypeError: Cannot read property of stateId
What am I doing wrong?
The issue with this was that state.getId() itself is undefined; and thus getting the property of stateId of state.getId() was the issue. This is not the same as the other question because a) it was not immediately clear that .getId().stateId was a property of undefined.
try
if(!state || !state.getId() || typeof state.getId().stateId === "undefined") {
console.log("Undefined");
} else {
console.log("Not undefined");
}
If either state or the value returned from the call to getId are undefined then you will get an error. The short circuit or test will catch it and stop you trying to access a property on undefined which is what is causing your error.
check if state.getId() is truthy first then check his property
if (state.getId() && state.getId().stateId !== "undefined") {
console.log("Not undefined");
} else {
console.log("Undefined");
}
Check if state exists, then check that state.getId is a function:
if (typeof state == "object" &&
typeof state.getId == "function" ) {
var id = state.getId();
console.log("stateId=",id.stateId);
} else {
console.log("Undefined");
}
For more information, see
MDN JavaScript Reference - Logical Operator - Short Circuit Evaluation

Undefined is not an object - Angular $rootScope.user.userMessage

I keep getting an error of
Error: undefined is not an object (evaluating '$rootScope.user.userMessage')
with this code:
if (typeof($rootScope.user.userMessage) === null) {
but if I do have something in $rootScope.user.userMessage it doesn't crash. How can I perform a check to see if this is undefined or null so that the thing doesn't break?
other things i've tried include:
if (typeof($rootScope.user.userMessage) === undefined) {
if ($rootScope.user.userMessage === undefined) {
if($rootScope.user && $rootScope.user.userMessage){
...
}
Typeof is not a function. You have to use it this way
if (typeof $rootScope.user.userMessage === "undefined") {
You can make the expression null safe
if ($rootScope !=null && $rootScope.user!=null && $rootScope.user.userMessage != null) {
...
}
if you are checking for only undefined you can use
angular.isDefined($rootScope.user.userMessage);
or
angular.isUndefined($rootScope.user.userMessage);
but the beat practices is to use
if($rootScope.user && $rootScope.user.userMessage){
...
}
it will check both null,undefined or empty within only one condition.

How to verify if creativeId is null

I was using this piece of code to verify if the creativeId is null, but it suddenly stopped working.
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
if(event.slot.k.indexOf('_super_superior')>0) {
if(event.creativeId!=null) {
alert('DFP');
}
else {
alert('Adsense');
}
}
});
It seems that creativeId is now always undefined and then I can't run the function.
Is there any other way to verify if creativeId is null so I can detect what ad is DFP and what is AdX?
Thanks!
Your code, as written, will distinguish between null and non-null values however null is not the same as undefined.
To test explicitly for null:
if (event.creativeId === null) { ... }
To test explicitly for undefined:
if (event.creativeId === undefined) { ... } // preferred by Crockford
or
if (typeof event.creativeId === 'undefined') { ... }
Given your existing logic, you may simply want to use "falsiness" to control branching:
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
if (event.slot.k.indexOf('_super_superior') > 0) {
if (event.creativeId) { // if event.creativeId exists / is numeric and non-zero / is a non-empty string / etc.
alert('DFP');
} else {
alert('Adsense');
}
}
});
You may try like this:
if(event.creativeId!=null || event.creativeId!= undefined)
Try this, checking against the string 'undefined' doesn't work as undefined is not a string, the string 'undefined' is when checked against typeof result.
if (event.creativeId!=null || event.creativeId != undefined)
JS Fiddle
The typeof way would be something like this instead typeof event.creativeId !== 'undefined'

Javascript test ( object && object !== "null" && object !== "undefined" )

I seem to be using this test a lot
if( object && object !== "null" && object !== "undefined" ){
doSomething();
}
on objects I get back from a service call or from reading cookies (since different browsers return the different values null, undefined, "null", or "undefined").
Is there an easier/more efficient way of doing this check?
I don't think you can make that any simpler, but you could certainly refactor that logic into a function:
function isRealValue(obj)
{
return obj && obj !== 'null' && obj !== 'undefined';
}
Then, at least your code becomes:
if (isRealValue(yourObject))
{
doSomething();
}
If you have jQuery, you could use $.isEmptyObject().
$.isEmptyObject(null)
$.isEmptyObject(undefined)
var obj = {}
$.isEmptyObject(obj)
All these calls will return true. Hope it helps
if(!!object){
doSomething();
}
If object is truthy, we already know that it is not null or undefined (assuming that the string values are a mistake). I assume that a not null and not undefined test is wanted.
If so, a simple comparison to null or undefined is to compare != null.
if( object != null ){
doSomething();
}
The doSomething function will run only if object is neither null nor undefined.
Maybe like this:
var myObj = {};
var isEmptyObj = !Object.keys(myObj).length;
if(isEmptyObj) {
// true
} else {
maybe like this
if (typeof object !== "undefined" || object !== null)
// do something
This should work without any issue.
if(object){ // checks for null and undefined
doSomething();
}
The best way to check if an object is empty is by using a utility function like the one below.
create a function
function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}
Use above function following way:-
So if you have an empty object, you can check whether it is empty by using the above function.
var myObj = {}; // Empty Object
if(isEmpty(myObj)) {
// Object is empty (Would return true in this example)
} else {
// Object is NOT empty
}
I think you could simplify a bit your logic with the following:
if (object != null && typeof(object) == "object") {
doSomething();
}
The main problem is that if you just check typeof(object) == "object", it will return true if object is null since null's type is "object". However, if you first check that object != null, you can be sure you are having something that is neither undefined nor null.
another simple way is
if (eval(object)) doSomething();
You can use eval to cast any type including string and be executed by javascript, here is eval documentation
If you want an Object, that is not an Array, and is not null, you might have to do some work, as all 3 will have the same typeof value.
if (
typeof maybeObject === 'object'
&& maybeObject !== null
&& !Array.isArray(maybeObject)) {
}

How to check 'undefined' value in jQuery

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
}
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.
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.
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
}
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.
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
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.
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')
}
})
I am not sure it is the best solution, but it works fine:
if($someObject['length']!=0){
//do someting
}
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
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
}

Categories

Resources