Checking if undefined in jQuery/Javascript - javascript

I have the following:
var currentQuestion = $(this).closest(".question")
I have tried everything suggested in this, this and this question:
if(currentQuestion !== undefined)
if(currentQuestion !== "undefined")
if(typeof currentQuestion !== undefined)
if(typeof currentQuestion !== "undefined")
if(currentQuestion !== null)
if(currentQuestion != undefined)
if(currentQuestion != "undefined")
if(currentQuestion.data("index") !== null)
if(currentQuestion.data("index") !== undefined)
if(typeof currentQuestion.data("index") !== undefined)
But it keeps going inside the if statement...
I have this inside the if:
console.log("nextQ: " + currentQuestion.data("index"));
and nextQ: undefined is getting print out
any other ideas?
EDIT:
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the one similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.

The result will never be undefined, it's always a jQuery object. If the operation didn't find any elements, the jQuery object will be empty, so you check how many element there are in it to see if found anything:
if (currentQuestion.length > 0)
After you have checked that there is actually any element in the jQuery object, you can check if there is any data associated to the element.
If no data is associated with an element, the data method will return undefined when you try to read the value. So, to check if there is no data, you should check the type of the value that the data method returns:
if (typeof currentQuestion.data("index") != "undefined")

If you want to check any elements exist, then check the length.
var currentQuestion = $(this).closest(".question");
if (currentQuestion.length > 0) {
console.log("nextQ: " + currentQuestion.data("index"));
}

if (currentQuestion.length) {
Should work fine. If it goes in there, it found something. And instead of looking at the if statement you need to look at your html and see what it found.

What you want is currentQuestion.length.
jQuery selectors return an array of elements matching the selector. To test for values in an array, you should use length:
Boolean([].length); //false
Because 0 evaluates to false, you can just use if (currentQuestion.length).
If you're trying to check for it when it is false, use !:
if (!currentQuestion.length)
For your question of why != worked but not !==, I would suggest this question: Difference between == and === in JavaScript
Basically, currentQuestion.data('index') is not strictly equal to null, but it could evaluate to null: same as [] == 0 evaluates to true, but [] === 0 evaluates to false.

It is probably not the most elegant solution. But somehow
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the most similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.

Related

Check of object length in Javascript

I want to check if my object is null or the length is 0. I have tried something like this without any luck.
if (this.get('goodie.pincodes.firstObject') == null || this.get('goodie.pincodes.firstObject.pin').length == 0) {
I solved this in a different way. Making sure that entries with no length allways returns null. Then only asking if the object is null.
this.get('goodie.pincodes.firstObject') == null

Jquery xml tag is exist or not

i am using Jquery and trying to find out whether below tag is exist or not
if(feed.mediaGroups[0].contents[0].thumbnails[0].url !== 'undefined') {
thumb = feed.mediaGroups[0].contents[0].thumbnails[0].url;
}
but this is crashing saying
TypeError: feed.mediaGroups is undefined
any idea ho i can get it worked.
Thank you
You're checking for a property a looong way down the chain, but clearly the feed object doesn't even have a mediaGroups property, so you should probably start there
if(
'mediaGroups' in feed &&
Array.isArray(feed.mediaGroups) &&
'contents' in feed.mediaGroups[0] &&
Array.isArray(feed.mediaGroups[0].contents) &&
'thumbnails' in feed.mediaGroups[0].contents[0] &&
Array.isArray(feed.mediaGroups[0].contents[0].thumbnails) &&
'url' in feed.mediaGroups[0].contents[0].thumbnails[0] &&
typeof feed.mediaGroups[0].contents[0].thumbnails[0].url !== 'undefined'
) {
thumb = feed.mediaGroups[0].contents[0].thumbnails[0].url;
}
you can see how this gets really tedious, and we didn't even check everything, we could still check if the arrays have a value at the index 0 etc, so knowing what to expect is really helpful, and you shouldn't really have to check each and every property in this way

does object/array exist in javascript

I'm trying to put content from RSS feed - problem is every RSS feed has different formats for images, content etc.
I'm trying to see if certain object exists in javascript or jquery:
item.mediaGroups[0].contents[0].url
How can I check it in an if statement? I keep getting for feeds without this structure:
Uncaught TypeError: Cannot read property '0' of undefined
Also tried:
if (typeof item.mediaGroups[0].contents[0].url === "undefined")
but I keep getting the same error.
thanks!
There is no "simple" built in way to do this sort of in depth checking. The reasoning is simple - most of the time you know the type of the objects you're working against.
You can do:
if (typeof item !== "undefined" &&
typeof item.mediaGroups !== "undefined" &&
typeof item.mediaGroups[0] !== "undefined" &&
typeof item.megiaGroups[0].contents !== "undefined" &&
typeof item.megiaGroups[0].contents[0] !== "undefined" &&
typeof item.mediaGroups[0].contents[0].url !== "undefined"){
When you type all that you might want to consider your data structures, since this really is not a situation you should be in to begin with :)
(hint, you can skip the typeof on all but the first, but I think typeof is a good clarification here).
The real question is this:
Why are you not sure what the structure of your data is?
If you are querying data (for example XML in an RSS feed) there are effective ways to do so with XPATH or query selectors. Object property access is built for objects where what you're querying is a document. Sure, it's possible with a bunch of ugly checks just like you can hammer a nail in with a heavy screwdriver.
You can see this question in Stack Overflow on how to use DOM methods to parse XML.
If you're uncertain about the exisence of properties, try this helper function:
function getProperty(root) {
var l = arguments.length, i, undefined;
for( i=1; i<l; i++) {
if( typeof root[arguments[i]] == "undefined") return undefined;
root = root[arguments[i]];
}
return root;
}
You can then call it like this:
var url = getProperty(item,'mediaGroups',0,'contents',0,'url');
As a more "haxy" way, you can try this:
try {url = item.mediaGroups[0].contents[0].url;}
catch(e) {url = undefined;}
I would check the length of both arrays in this case to be sure - before assuming there are objects defined at index 0
item.mediaGroups.length > 0
and
item.mediaGroups[0].contents.length > 0
As the outer check you can also throw in a
if(item.mediaGroups){
}
How about 'optional chaining' (described in ES2021 spec and already implemented in all browsers except three) ?
from MDN:
The optional chaining operator provides a way to simplify accessing
values through connected objects when it's possible that a reference
or function may be undefined or null.
The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined so it is giving us a way to handle the possibly undefined/nullsish values
item?.mediaGroups[0]?.contents[0]?.url // will evaluates to undefined if either of those is undefined.
item.mediaGroups[0].contents is undefined, you have to check for it.
if(item.mediaGroups && item.mediaGroups[0].contents) {
return item.mediaGroups[0].contents[0].url;
}
It's not a solution with if-statements (as requested), but you can use exceptions to achieve similar functionality. Something like this:
function throwOrReturn(thing){
if(typeof thing === 'undefined'){
throw "Didn't find it..."
}else{
return thing
}
}
// The unknown thing.
var a = {
b1: {
},
b2: {
c: 'lookingFor'
}
}
var c
// Test our different paths.
try{
// First guess.
c = throwOrReturn(a.b1.c.d)+" - a.b1.c.d"
}catch(error){
try{
// Second guess.
c = throwOrReturn(a.b[45][34].c)+" - a.b[45][34].c"
}catch(error){
try{
// Third guess.
c = throwOrReturn(a.b2.c)+" - a.b2.c"
}catch(error){
// Try more guesses, or give up.
c = "notFound"
}
}
}
console.log("c:", c) // Logs: "c: lookingFor - a.b2.c"
It ain't pretty, but it's an alternative worth to mention.

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

JQuery - write conditional when object property is blank

I'm trying to write a conditional for when an object property's value is blank, but it is not triggering. This is my code. Any idea how I should write this?
console.log(vid);
if (vid.video == undefined){
//DO STUFF HERE - Doesn't work
}
The "object" in the screenshot is referenced in the code above as variable vid. I also tried undefined in the conditional.
I see some misunderstading here:
You say when an object property's value is blank but your coded if (vid.video != ""){.
I think you need if (!vid.video) {
use this:
vid.video == undefined
Also what Andrew said. If you want to DO STUFF when the attribute is empty, you should Use "==", and not "!="
if(vid.video != "")
Are you looking to only execute code when video doesn't equal "" but if you want to execute code when it is equal to "" you need
if(vid.video == "")
However if you want to check to see if its undefined you'll need to do
if(vid.video === undefined){
vid.video is not defined here
}
or
if(vid.video){
vid.video is defined here
}

Categories

Resources