Copy link to clipboard
Copied
Hi everybody. I'm confused about how nested ternary operators work in extendscript. I have th folowing code:
function toStringArray(source) {
var newArray = _.isArray(source) ? 'Source is Array'
: _.isString(source) ? 'Source is String'
: 'Source is undefined'
return newArray
}
//Output:
//toStringArray() => 'Source is undefined'
//toStringArray('My string') => 'Source is String'
//toStringArray(['My string']) => 'Source is String' ¿?
In regular Javascript and Adobe Animate scripts this code works as expected, but not in extendscript. ¿Why is an Array not evaluated as 'Source is Array'?
Its just a side effect of ExtendScript being a very old JavaScript dialect. JavaScript got much better over time and many of those improvements are simply not yet available in ExtendScript. I agree that the brackets are hard to read for many nested ternary statements. If you want to write clean code, if else is probably your best option, also if the redundant variable assignments in each case are not ideal.
Copy link to clipboard
Copied
I know for || and && that the operator precedence of ExtendScript is different to other, more modern JavaScript dialects. Maybe this is the same for the ternary?
That would mean that ExtendScript reads
_.isArray(source) ? 'Source is Array'
: _.isString(source) ? 'Source is String'
: 'Source is undefined'
as
(_.isArray(source) ? 'Source is Array'
: _.isString(source)) ? 'Source is String'
: 'Source is undefined'
and you should be able to fix it by setting the brackets explicitly to
_.isArray(source) ? 'Source is Array'
: (_.isString(source) ? 'Source is String'
: 'Source is undefined')
Copy link to clipboard
Copied
Thanks Mathias! I thought about that aproach before asking, I've tyed to simplify the problem as mutch it can be simplified, but...What if I need about 3, 4 or X expressions need to be evaluated?
'if else' statments still there, but I just want to understand: What kind of ancient witchcraft makes this operators behave like this?
Copy link to clipboard
Copied
Its just a side effect of ExtendScript being a very old JavaScript dialect. JavaScript got much better over time and many of those improvements are simply not yet available in ExtendScript. I agree that the brackets are hard to read for many nested ternary statements. If you want to write clean code, if else is probably your best option, also if the redundant variable assignments in each case are not ideal.
Copy link to clipboard
Copied
Hmmm, I see. Thanx for the explanation! Well, maybe I'll go for some kind of function that can reduce the syntax of the code, something like this:
function customSwitch(){
for(var i = 0, len = arguments.length; i < len; i += 2){
if(arguments[i] === true) return arguments[i +1]
}
}
customSwitch(
_.isArray(source),
source,
_.isString(source),
[source],
true,
[]
)
Get ready! An upgraded Adobe Community experience is coming in January.
Learn more