A few days ago, I was working on JSOM (JavaScript object model) on SharePoint Online. As per the business requirement, I had to check if he/she is a member of a particular SP Group or not. In that scenario, I used the following code.

Steps to use the code

To use the code, this function can be added to the targeted code file or to use in a SharePoint custom list forms or in a page. Adding to the Script Editor web part or Content Editor web part will be a good choice.

The following function named "IsGroupMember" is the function which returns a boolean value with True/False. And this function gets three parameters - the name of the Group, the user from whom we want to check, and the ClientContext. Also, it is important to mention that with groupName variable, a string value as the group visual name needs to be sent and with cUser variable, SPUser's user name needs to be sent.

Code Snippet
  1. function IsGroupMember(groupName, cUser, clientContext) {
  2. var deferred = $.Deferred();
  3. var currentWeb = clientContext.get_web();
  4. var allGroups = currentWeb.get_siteGroups();
  5. clientContext.load(allGroups);
  6. var group = allGroups.getByName(groupName);
  7. clientContext.load(group);
  8. var groupUsers = group.get_users();
  9. clientContext.load(groupUsers);
  10. clientContext.executeQueryAsync(
  11. function onQuerySucceeded(sender, args) {
  12. var isUserInGroup = false;
  13. var groupUserEnumerator = groupUsers.getEnumerator();
  14. while (groupUserEnumerator.moveNext()) {
  15. var groupUser = groupUserEnumerator.get_current();
  16. if (groupUser.get_id() == cUser.get_id()) {
  17. isUserInGroup = true;
  18. break;
  19. }
  20. }
  21. deferred.resolve(isUserInGroup);
  22. },
  23. function onQueryFailed(sender, args) {
  24. console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  25. deferred.resolve(false);
  26. //if the funtion got ay error, it will return false.
  27. }
  28. );
  29. return deferred.promise();
  30. }

Notes
In this code snippet, deferred - promise is used to increase the usability. This can be ignored if the developer wants to simply return the value or can use onComplete function.