How to check if the user exists in a particular SharePoint group using ECMAScript

In this blog you will see how to check if the user exists in a particular SharePoint group using ECMAScript.
 
  1. <script type="text/javascript">  
  2. ExecuteOrDelayUntilScriptLoaded(IsUserExists, "sp.js");  
  3.   
  4. var group;  
  5. var users;  
  6. var ctx;   
  7. var groupCollection;  
  8. var user;  
  9. var currentuser;  
  10.   
  11. function IsUserExists() {  
  12.    ctx = SP.ClientContext.get_current();  
  13.    groupCollection = ctx.get_web().get_siteGroups();  
  14.    currentuser=ctx.get_web().get_currentUser();  
  15.    group = groupCollection.getById(4103);  
  16.    ctx.load(group);  
  17.    ctx.load(currentuser);  
  18.    ctx.executeQueryAsync(Function.createDelegate(thisthis.OnGetGroupSuccess), Function.createDelegate(this, OnFailure));  
  19. }  
  20.   
  21. function OnGetGroupSuccess() {  
  22.     users=group.get_users();  
  23.     ctx.load(users);  
  24.     ctx.executeQueryAsync(Function.createDelegate(thisthis.OnGetuserSuccess), Function.createDelegate(this, OnFailure));   
  25. }  
  26.   
  27. function OnGetuserSuccess() {     
  28.     var userEnumerator = users.getEnumerator();    
  29.     while (userEnumerator.moveNext()) {  
  30.            var user = userEnumerator.get_current();  
  31.            if (user.get_id() == currentuser.get_id()) {  
  32.                    alert("User Exists")                          
  33.                    break;  
  34.                 }  
  35.                 else  
  36.                 {                     
  37.                 }  
  38.             }  
  39.          }  
  40.   
  41. function OnFailure(sender, args) {  
  42.   alert("Failed to execute IsCurrentUserMemberOfGroup method");  
  43. }  
  44. </script>