Extendscript (JS): How to guard undefined object properties?

Copy link to clipboard
Copied
Just picked up this Extendscript for a quick utility function. I can't seem to use any of the "usual" Javascript logic contstructs to test for undefined object properties.
Example:
typeof(app.activeDocument) === "undefined"
This is an *error* in Extendscript (Error 1302: No such element). I don't believe it should be, but if I'm supposed to do something different in Extendscript I am all ears.
Thank you
Edit: Now posted to the correct forum.
Explore related tutorials & articles
Copy link to clipboard
Copied
You would do something like...
if(documents.length){
alert(typeof(app.activeDocument));
}else{
alert("There are no documents open.");
}
or use a try catch

Copy link to clipboard
Copied
I considered that as a solution, I guess I was hoping for an answer on why Extendscript doesn't support a common Javascript nomenclature (unless I'm mistaken and Extendscript isn't supposed to resemble Javascript).
No worries, thanks for the reply.
Copy link to clipboard
Copied
You could fix up something like:
var nicer_obj = function (obj) { var new_obj = {} for (key in obj) { if (obj.hasOwnProperty(key)) { try { new_obj[key] = obj[key]; } catch (err) {} } } return new_obj; }
typeof nicer_obj(app).activeDocument; // 'undefined' or 'object'
For what it’s worth, I also think it’s really stupid and annoying that the built-in objects don’t behave at all like you’d expect typical ECMAScript objects to behave. Browsers used to have similar quirks (which is why everyone just uses jQuery), but many of those have been worked out by now.
Copy link to clipboard
Copied
There are several properties that will throw an exception if the property is not defined. Using app.documents.length is the correct technique to use before accessing app.activeDocument.
This was a deliberate, though unfortunate, design decision on the part of Adobe. We discussed this in depth a few years ago.
-X
Copy link to clipboard
Copied
Do you have a link to that discussion? It’s clearly a deliberate API decision; I just think it’s annoying. Copying all the properties to a new object as with that nicer_obj function is a perfectly reasonable alternative method though, especially if you care about other properties beyond activeDocument that might or might not be set. (I don’t have any idea what those would be.)
Copy link to clipboard
Copied
Do you have a link to that discussion?
The discussion was probably on ps-scripts.com or maybe the older (pre-Jive) Adobe PS Scripting forum. I don't have a link.
It’s clearly a deliberate API decision; I just think it’s annoying.
That was the general consensus.

