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

Issue encountered while attempting to install datagrid library with Nuxt3

Currently, I am working on a Nuxt3 project and attempting to integrate the " @revolist/vue3-datagrid" library. Following the instructions provided in the library's documentation, I executed the command "npm i @revolist/vue3-datagrid --save". Unfortuna ...

Method for testing with Jest

I'm relatively new to Jest and I've been having trouble testing this particular JavaScript method: const parseData = (items) => { const data = []; const itemsCount = items.length; for (let i = 0; i < itemsCount; i += 1) { const el ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

exploring various dynamic elements using jquery

If you need some help figuring this out, take a look at the JSFiddle here. I've set it up for users to input any data they want in the text box, choose a table from set one, and then click the "submit" button to send it. <div> <Div> < ...

Why isn't my onScroll event triggering in my React.js application? What mistake am I making?

I am facing an issue with my onScroll event in react js. My goal is to implement infinite scrolling in react js, but unfortunately, the onScroll event is not triggering as expected. The process involves fetching posts from an API and passing them to the ...

Maintaining checkbox state using fetch arrays

Included below is the code present on my site, pulling data for each season including numbers of home wins, win percentage, and win lsp. It functions correctly by creating a new table row for each season. Furthermore, there are two columns featuring filte ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

React Router updates the URL path without actually rendering the content of the second page

I'm having an issue with my React app where the address changes correctly in the search bar, but the page is not loading. Here is my code: import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; i ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

Guide to enclosing selected text within a span tag and positioning a div in relation to it using JavaScript

My main objective is to enable the user to: highlight text within a paragraph enclose the highlighted text in a span element add an action button or div at the end of the selected text for further interaction Here's the code I've worked on so ...

If the currency is not in USD, please refrain from using the $ symbol before the amount

Is it possible to modify this function so that when the currency is not USD, the $ sign is not added in front of the amount? var convertToCurrency = number => { if (!number) return ''; return new Intl.NumberFormat('en', { ...

Tips for storing multiple pieces of text in HTML5 local storage

I have been working on creating functions and input boxes within a table to display data upon page reload. However, I am encountering difficulties in understanding how to store multiple inputs in local storage and then loop through them to show all the d ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

Having several contact forms embedded within a single webpage

I am currently in the process of developing a prototype website and my objective is to have multiple forms on a single page. My goal is to have a form for each service, where users can click on the service and fill out a form to request a quote. The first ...

Incorporate a new class for every date within the range of start and end

I have incorporated a JQuery event calendar plugin into my project, sourced from this specific website. Within my events, there are distinct start and end dates. Currently, I have managed to display green squares on the calendar for both the start and end ...

Using Selenium WebDriver with JavaScript: Handling Mouse Events (mouseover, click, keyup) in Selenium WebDriver

I am currently working on integrating Selenium testing for mouse events with dynamically generated elements. Specifically, I am attempting to trigger a "mouseover" event on an element and then interact with some icons within it. However, I have encountere ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...