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

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.

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 can I test if response.location.id is defined?

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)).

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