Adjust the variable value if the "for" loop encounters an error

In my situation, I have a spreadsheet that contains a script responsible for checking another linked spreadsheet for a customer's name and then returning the associated code. Everything works smoothly when the customer name is found in the "CustomerCodes" sheet that the script references. However, if the customer name does not exist in that sheet, I want to ensure that the variable value "customerCode" is set to "No match found." Currently, the script throws an error and stops running if the customer name cannot be located in the referenced sheet. Below is the snippet of the code in question:

var customerName = sheet.getRange('I2').getValue();
  
  var ccsheet = ss.getSheetByName("CustomerCodes");
  var lastRow = ccsheet.getLastRow();
  
  Logger.log("lastRow: " + lastRow);
  
  var lookUp = ccsheet.getRange(2, 1, lastRow, 3).getValues();
  
  for (nn=0; nn<lookUp.length; ++nn) {
    if (lookUp[nn][0] == customerName) {break}
  }

  //This is where I am having the trouble 
  var customerCode = lookUp[nn][1];
  
  Logger.log("customerCode: " + customerCode);

If the "for" loop successfully finds a matching customer name, it sets the "customerCode" variable to that specific match. In cases where no match is found, I aim to have the "customerCode" variable indicate "No match found," providing clarity to users as to why the customer's code was not returned. This value stored in the "customerCode" variable is later delivered to the user within the function.

Being relatively new to scripting, I lack a strong understanding of error handling and couldn't find comprehensive Google Apps Script documentation on the topic. Any assistance you can provide would be greatly appreciated!

Answer №1

To determine if there is a match, it's important to add code that checks for it. Another approach would be to verify whether the variable nn is smaller than the length.

var matchIndex = -1;
for (var nn=0; nn<lookUp.length; ++nn) {
    if (lookUp[nn][0] == customerName) {
        matchIndex=nn;
        break;
    }
}

//I am encountering difficulty at this point
var customerCode = matchIndex===-1 ? "Not found" : lookUp[matchIndex][1];

Answer №2

If you're looking for information, there are multiple methods to achieve the desired outcome. A more direct and easily readable approach can be seen in this snippet of code:

var customerCode = 'no customer with this ID found in the list';
for (var nn=0; nn<lookUp.length; ++nn) {
    if (lookUp[nn][0] == customerName) {
        customerCode = lookUp[nn][1];
        break;
    }
}

This alternative accomplishes the same result without relying on the shorthand IF THEN ELSE statement (also known as the ternary operator) mentioned above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

Would it be considered improper to implement an endless loop within a Vue.js instance for the purpose of continuously generating predictions with Tensorflow.js?

In my project, I am leveraging different technologies such as Tensorflow.js for training and predicting foods, Web API to access the webcam in my notebook, and Vue.js to create a simple web page. Within the addExample() method, there is an infinite loop r ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...

Passing URL parameters from App.js to routes/index.js

I have a URL that looks like this: http://localhost:3000/?url=test In my Express application's app.js file, I'm attempting to extract the "test" parameter from the URL and pass it to my routes/index.js. Currently, I can easily send a static var ...

Tips for reconstructing a path in Raphael JS

I am encountering a unique issue with my implementation of Raphael JS. Currently, I am working on drawing a donut element and seeking advice similar to the content found in this helpful link How to achieve 'donut holes' with paths in Raphael) var ...

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

Using Jquery to toggle the visibility of a DIV element and adding a blinking effect when it becomes visible

I have a hidden div that is displayed when a link is clicked, and I want it to blink as well. Here is my current setup: The link to display the hidden div: <a class="buttons" href="#" onclick="show(this)">join us</a> The hidden div to be di ...

Modifying several items with Ramda's lens

I am currently working with a data structure that is structured similarly to the following: var data = { "id": 123, "modules": [{ "id": 1, "results": [{ "status": "fail", "issues": [ {"type": "ch ...

Maintaining AngularJS Authentication Securengular: Ensuring

I need to find the ideal architectural solution. Below is the HTML code I currently have: <body ng-controller="individualFootprintController as $ctrl"> <div ng-hide="$ctrl.authenticated"> <h1>Login</h1> Wit ...

What is the proper way to send a list of lists from Ajax to Flask?

Attempting to send a list of list datatype data from a template using AJAX. Here is the code: Template (JS) var mydata = [['tom', 18, 'new york'], ['jack', 16, 'london']]; var data = new FormData(); mydata.forEach( ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Transfer data between an HTML page and a PHP page hosted on separate locations using jQuery

Below is the code snippet I am currently working on: function send_data() { var a=$("#username").val(); var b=$("#password").val(); $.post("http://localhost/login/login.php", {uname: a, pswd: b}, function(data) { $("#result").html(data); }); ...

JavaScript Date behaving oddly

While working with Javascript, I encountered a puzzling issue involving the Date object. date1 = new Date(1970, 1, 1); date2 = new Date("1970-01-01T13:00:00.000Z"); console.log(date1.getYear()); //70 console.log(date1.getMonth()); //1 console.log(date1.g ...

I'm facing some difficulties in sourcing my header into a component and encountering errors. Can anyone advise me on how to properly outsource my header?

Looking to streamline my headers in my Ionic 4 project by creating a separate reusable component for them. Here's how I set up my dashboard page with the header component: <ion-header> <app-header title="Dashboard"></app-he ...

How can I ensure that I only include a field in a JavaScript object if the value is not null?

In my current setup, I am utilizing mongoose to write data to a MongoDB collection while ensuring there are no null fields. Default values have been set in the document for this purpose. During an update function call, certain fields may be null but I do n ...

Having trouble with the ionic ion-nav-buttons not working on initial load?

My table view triggers the PixCtrl controller when a cell is clicked. If the connection is successful, data is retrieved using $http.get, otherwise sqlite is used. This setup works fine. However, I am facing an issue with my ion-nav-buttons being dynamic. ...

Tips on integrating the createjs library into a ReactJS project

Hey there! I'm currently working on developing a canvas-based app using ReactJS, and I need to integrate the CreateJS library. As a newcomer to ReactJS, I've been struggling to figure out the best approach. I've tried two different methods - ...

Setting default property values in a React component using Typescript

   Is there a way to define default property values in React components when using Typescript? I came across a post on SE suggesting the use of a static class variable called defaultProps with key-value pairs for properties. However, this method didn&a ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...