How can I test if response.location.id is defined? - javascript

How can I test if :
response.location.id
is defined ?
Thank you

if (response && response.location && typeof response.location.id !== "undefined"){
// is defined
}

typeof response.location.id !== "undefined"
If you can't depend upon the rest being defined, then:
response && response.location && typeof response.location.id !== "undefined"
If you can depend on them, and don't have to worry about null, false or 0 as values for a defined id, then just test it directly (if(response.location.id)).

Related

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.

"Cannot read property .. of null" after checking for undefined object

I have an object that I need to check if it is defined. Also, I also want to check if a property of that object is true or false.
So what I want is
if ((typeof myVar !== 'undefined') && (myVar.isMale === false)) {
// Do something 1
}
else{
// Do something 2
}
But this logic gives me error
Uncaught TypeError: Cannot read property 'isMale' of null
What will be the best login to handle this condition ?
Thanks !
You need to test further, either by exclusion:
if (typeof myVar != 'undefined' && myVar && myVar.isMale === false) {
or by inclusion:
if (typeof myVar == 'object' && mVar && myVar.isMale === false) {
but there are objects that return values other than "object" with typeof tests (e.g. host objects may and Function objects do).
or by explicit conversion:
if (typeof myVar != 'undefined' && Object(myVar).isMale === false) {
Edit
The additional && myVar test is to catch NaN and null which pass the typeof test.

How to check isEmpty in javascript

I want to check the response.data.totalRows is empty.
if (response!=undefined
&& response.data!=undefined
&& response.data.totalRows!=undefined) {
alert(response.data.totalRows);
}
Can simplify the code?
UPDATE: it seems that there is no simple method like isEmpty(response.data.totalRows).
Yea, you can simply do this:
if (response && response.data && response.data.totalRows) {
alert(response.data.totalRows);
}
In JavaScript, a object is cast to a truthy value, when used in a if. This means you can just "dump" the variable in a if or any other boolean statement, as a check to see whether or not it exists. this blog post has some more information about it.
Please note that this will not alert anything if totalRows equals 0 (since 0 is considered a falsy value.) If you also want to alert if it's 0, use this:
if (response && response.data &&
(response.data.totalRows || response.data.totalRows === 0)) {
alert(response.data.totalRows);
}
Or:
if (response && response.data && response.data.totalRows !== undefined) {
alert(response.data.totalRows);
}
Supposing that response.data.totalRows must be an array you can use just:
if (!response.data.totalRows.length) {
/* empty array */
}
If you are not sure that totalRows exists you must verify:
if (
!response ||
!response.data ||
!response.data.totalRows ||
!response.data.totalRows.length
) {
/* is empty */
}
Any value is converted in Boolean. For example: Boolean(response) will return false if response will be 0, null, undefined etc.
What about a try-catch block?
try{ alert(response.data.totalRows); }
catch(e) { alert("undefined"); }
I'd write a prototype (even if it's not recommended)
Object.prototype.isEmpty = function(){
return (!this || this===undefined || this===null || !this.hasChildNodes())
?true
:false;
}
And then just use
if(!response.isEmpty()) alert(response.data.totalRows);
It is only handy if you need the checks also elsewhere and not only one place.
Just
response && response.data && response.data.totalRows && alert(response.data.totalRows)
If the property list gets very long there is another syntax you can use, in the sample code I've created a function so it can be re used.
// args is { object: the object to check the properties of
// properties: an array of strings with property names}
function isSet(args){
//no checking of arguments
var o = args.object,
props = args.properties,
i = -1,len = props.length
while(typeof o !== "undefined"
&& o !== null
&& ++i<len){
o = o[props[i]];
}
return (typeof o !== "undefined"
&& o !== null)?true:false;
}
var test = {
prop1 : {
prop2 : "ok"
}
};
//check if test.prop1.prop2 is set
console.log(isSet({
object:test,
properties: ["prop1","prop2"]
}));//=true

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
}

MyApphow to check for "typeof MyApp.User.current.language" [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
javascript test for existence of nested object key
if (typeof MyApp != 'undefined' &&
typeof MyApp.User != 'undefined' &&
typeof MyApp.User.current != 'undefined' &&
typeof MyApp.User.current.language != 'undefined') {
console.log(MyApp.User.current.language);
}
this feels wrong. Can this if statement be written in some nicer way?
You could perform a decompose conditional refactoring and put that condition in a function:
if (currentLanguageIsDefined()) {
console.log(MyApp.User.current.language);
}
function currentLanguageIsDefined() {
return typeof MyApp != 'undefined' &&
typeof MyApp.User != 'undefined' &&
typeof MyApp.User.current != 'undefined' &&
typeof MyApp.User.current.language != 'undefined';
}
... or you can take advantage of the fact that the && operator returns the last value evaluated:
var lang;
if(lang = getCurrentLang()) {
console.log(lang);
}
function getCurrentLang() {
return MyApp && MyApp.User && MyApp.User.current && MyApp.User.current.language;
}
One simple way is this:
try {
console.log(MyApp.User.current.language);
} catch(e) {}
or if you don't want "undefined" to be output if MyApp.User.current exists, but MyApp.User.current.language does not, then you would use this:
try {
if (typeof MyApp.User.current.language != 'undefined') {
console.log(MyApp.User.current.language);
}
} catch(e) {}
The try/catch catches the cases for when MyApp or MyApp.user or MyApp.User.current are not defined so you don't have to test for them individually.

Categories

Resources