SharePoint Online - Check If A User Is In A Group With JSOM

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

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.