Invalid Function definition Error in logs

Tapish Sharma1
Kilo Sage

Hi All, 

I am using below script in scheduled reports to check the month, but the script is not working 

It shows invalid function def in logs

function checkMonths(){

var a = false;
var triggerMonths = [1,3,5,7,9,11];
var currentDate = new Date();
var currentMonth = currentDate.getMonth();


for (i in triggerMonths){
if ( currentMonth == triggerMonths[i])
a=true;
}
return a;
}


checkMonths();

 

TapishSharma1_0-1668082117580.png

 

9 REPLIES 9

Hi @Tapish Sharma1 

 

I guess no need to create a function, you can directly check the condition as below:

 

var triggerMonths = [1,3,5,7,9,11];
var currentDate = new Date();
var currentMonth = currentDate.getMonth();

for (i in triggerMonths){
if ( currentMonth == triggerMonths[i])
return true;
}
return false;

 

 

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

Thanks
Anubhav Ritolia
ServiceNow Rising Star 2023

You cannot have a return statement without function

Abhijit4
Mega Sage

Try below code :

function checkMonths(){
var triggerMonths = [1,3,5,7,9,11];
var currentDate = new Date();
var currentMonth = currentDate.getMonth();


for (var i=0;i< triggerMonths.length;i++){
if ( currentMonth == triggerMonths[i])
return true;
}
return false;
}


checkMonths();

 

Please mark answer as Correct or Helpful based on impact.

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

Your logic is not efficient one, please use below logic which is way more efficient :

 

function checkMonths(){
var currentDate = new Date();
var currentMonth = currentDate.getMonth();
if ( currentMonth%2 == 1)
return true;
}
return false;
}
checkMonths();

 Please mark answer as Correct or Helpful based on impact.

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

Tapish Sharma1
Kilo Sage

I have found the solution, function definition is not supported in conditional scripting as it is sandbox script. please use script include to do something like this,