title: Error when assigning auto-created label to threads (TypeError: thread[t].addLabel is not a function) - google app script
body: <p>I'm trying to assign auto-created label to gmail threads. The label alone was successfully created but it couldn't be assigned to the respective threads due to a TypeError.</p>
  <p>Here's the script</p>
  <pre><code>//call cell value by column (Sheet: &quot;SupplierNumber&quot;)
  //label created based on the &quot;Label&quot; column in Sheet: SupplierNumber
  //Label applied to related threads
  
  function callLabelcolumn() 
  {
    var ss = SpreadsheetApp.getActive();
    
    var sh = ss.getSheetByName('SupplierNumber');
    var rg=sh.getRange('A2:A');
    var vA=rg.getValues();
  
    var sh3 = ss.getSheetByName(&quot;SearchParameter&quot;)
    var rg3=sh3.getRange('A2');
    var searchPara =rg3.getValues();  
  
    var threads = GmailApp.search(searchPara);
    
            
    for (var i = 0; i &lt; threads.length; i++){
      var msg = threads[i].getMessages();
      for (var j = 0; j &lt; msg.length; j++){
              
        // Get same thread by its ID.
        //var threadID = GmailApp.getThreadById(msg[j].getId());
        var msgid = msg[j].getId();
        } 
    }
  
  
    vA.forEach(function(row) {
    if(row != &quot;&quot; &amp;&amp; row != &quot;#N/A&quot;){
     
     Logger.log('Label: %s', row);
      var label = GmailApp.createLabel(row);
      
     Logger.log(&quot;label: &quot; + label);
               
     }  
       
      var thread = [0];
      var thread = GmailApp.getMessageById(msgid).getThread().getId();
      var name = GmailApp.getUserLabelByName(label.getName())
  
       for(var t in thread){
      console.log(&quot;So far so good. Let's add label&quot;)
      thread[t].addLabel(name);
        }
    
  
    });
  
     
  }
  </code></pre>
  <p>The error is &quot; TypeError: thread[t].addLabel is not a function &quot; when run script in the editor.
  <a href="https://i.stack.imgur.com/c41ux.png" rel="nofollow noreferrer">TypeError: thread[t].addLabel is not a function</a></p>
  <p>After debugging, I'm suspecting var name returned &quot;&quot; or null which is why the error is happening.</p>
  <p><a href="https://i.stack.imgur.com/zcKB2.png" rel="nofollow noreferrer">Debug result: thread[t].addLabel</a></p>
  <p>I tried debugging on var name, some of results were name: undefined, t: undefined which I think is the cause of the TypeError.</p>
  <p><a href="https://i.stack.imgur.com/SB2jy.png" rel="nofollow noreferrer">Debug result: var name = GmailApp.getUserLabelByName(label.getName())</a></p>
  <p>So is there a way to solve this?</p>