We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

forEach Loop

Snow Tomcal
Tera Expert

Hi All,

I have a script include with a forEach Loop. I'm trying to call another function inside it but it is not being called.

I replaced the Loop with a for loop and it did worked.

 

the for loop:

for(i=0; i<groups.length; i++){

allUsers = arrayUtil.concat(allUsers, this.myFunction(tableName, 'group' = groups[i], variable));

}

 

the foreach loop:

groups.forEach(function(group){

allUsers = arrayUtil.concat(allUsers, this.myFunction(tableName, 'group' = group, variable));

}

 

Does anyone have an idea why is this happening?

Thanks in advance 🙂

1 ACCEPTED SOLUTION

Chaitanya ILCR
Giga Patron

Hi @Snow Tomcal 

 

when using iterative array methods (e.g., forEach, map, filter), the this value inside the callback is usually undefined.

 

https://www.w3schools.com/js/js_this.asp 

can you try this instead.

assign the function definition to a variable outside the forEach loop and pass it as the second parameter to the forEach

var myFunc =  this.myFunction

groups.forEach(function(group){

allUsers = arrayUtil.concat(allUsers, myFunc(tableName, 'group' = group, variable));

},myFunc);

 

Regards,
Chaitanya

View solution in original post

3 REPLIES 3

Chaitanya ILCR
Giga Patron

Hi @Snow Tomcal 

 

when using iterative array methods (e.g., forEach, map, filter), the this value inside the callback is usually undefined.

 

https://www.w3schools.com/js/js_this.asp 

can you try this instead.

assign the function definition to a variable outside the forEach loop and pass it as the second parameter to the forEach

var myFunc =  this.myFunction

groups.forEach(function(group){

allUsers = arrayUtil.concat(allUsers, myFunc(tableName, 'group' = group, variable));

},myFunc);

 

Regards,
Chaitanya

It worked!

Thanks:))

SyamPrasanM
Tera Expert

Hi @Snow Tomcal 
Hope this answere is useful to your question,

 

To resolve this  Use an Arrow Function

Arrow functions do not have their own this context; they inherit it from the enclosing scope. You can replace your forEach loop with an arrow function like this

 

Javascript code 

groups.forEach((group) => {
allUsers = arrayUtil.concat(allUsers, this.myFunction(tableName, 'group' = group, variable));
});


Regards,
Mule Syam Prasanna 

PRAVAL-LOGO.png