Error trying to iterate subtasks

Hello!
I have the following code and there is no way I can get it to work, every time I try to get the size of the subtask array to be able to loop through it, I get that error :

"Execution of custom JavaScript code raised the following error:
TypeError: Issue: GDPP-10, error: Cannot read property “length” from undefined"

Code:

if(issue.fields.customfield_11448 == "si"){
  var size = issue.fields.subtasks.length;
  
  var count = 0
  for(var i = 0; i < size; i++){
    if(issue.fields.subtasks[i].fields.issuetype.name == "Cambio de Alcance"){
      count++
    }
  }
return count
}else{
  return 0
}

I have a customfield_11448 flag = “yes” field that allows me to know if I have subtasks or not to only iterate those that have a value but still fails

Hi @Emiliano_Romero,

Even if you trust that data are correctly aligned for custom fields and subtasks, some issues have sub-tasks, and some might not.
Before addressing sub-task values or any other issue fields, you might want to validate if the object exists in the fits place. Use additional if() construction.

For example, before assigning variable size with sub-task count, check if the subtask object exists at all:

if(issue.fields.customfield_11448 == "si"){
  if(issue.fields.subtasks){
    var size = issue.fields.subtasks.length;
    ..

Note that you can test the custom field and JavaScript code on several issues before saving it. I would recommend testing the code always on several issues that would provide different results - without values or from projects with different workflow (New calculated fields).

Best,
Zane / support@eazyBI.com