When declaring a variable in a Google Apps script, when would I use let
vs. const
vs var
, as in the following?
let sheet = range.getSheet();
const sheet = range.getSheet():
var sheet = range.getSheet();
Different tutorials use different terms. Are they interchangeable? I'd like to choose correctly.
Next, when should one use get.Value()
vs get.Values()
? I thought one was for a single value and the other for an array of values, but was I thrown an error when reading an email address using get.Value()
. The error was: Error sending email to function () { [native code] }. The code worked when I changed it to get.Values()
.
Though the condition on using both is the same, they are expecting different parameters to receive. getValue gets a value of a cell, while the getValues gets 2D array.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = ss.getRange("A1:A5").getValues();
var range2 = ss.getRange("A1:A5").getValue();
console.log("getValues: " + range)
console.log("getValue: " + range2)
}
In the sample code above, the line that uses get values will return all values of the range while the line that uses get value will return only the top left value of the range though the range contains lots of values
getValue() and getValues() also differs from the type that they get, getValue() gets a single type value(string, number) while getValues() handles object types see the output of typeof() method below(which return the type of the parameter given)
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = ss.getRange("A1").getValues();
var range2 = ss.getRange("A1:A5").getValue();
console.log("getValues: " + typeof(range))
console.log("getValue: " + typeof(range2))
}
In your case, you might be encountering issue when using getValue due to the structure of the field where the email address is located, most likely, the data you're accessing (the email address) is part of a range or an item that is being returned as an array (even if it contains only one element)
In Google Apps Script, which is based on JavaScript, you have three main ways to declare variables: let
, const
, and var
. Each has its own use case and behavior.
let:
const:
var:
When you require a variable that can be changed later, use let. For values that shouldn't be changed, use const. In current JavaScript, avoid using var because of its scope-related peculiarities.
You can also check this post for more information: var, let and const as explained by Stackoverflow community
Reference: Var, Let, and Const – What's the Difference? getValue()