javascriptgoogle-sheetsformattingboolean

Newbie Help: Syntax error: SyntaxError: Unexpected identifier (JavaScript)


Armature coder here. I may be doing something simple wrong here but I'm basically wanting to have a Boolean determine what action is to be taken in a function that gets called later. While there is missing items such as cropped and croppedNmb don't worry as these are pre-defined in the whole script. Specifically I am using .gs but .gs is a JavaScript-Based coding format thingy.

Again, I'm super new so it could be a simple solution such as incorrect formatting.

function getFormat(format = String, textOrNumber = Boolean) { //0 = get text 1 = get number
  if textOrNumber = 0 {
    return cropped;
  }
  else if textOrNumber = 1 {
    croppedNmb = formattedValue.replace(cropped, '')
    return croppedNmb
  }
}

This would then be called later. For example, this is the test I'm using to see if the above function works (which it doesn't currently)

Logger.log(getFormat(currentRange, 1) + getFormat(currentRange, 0));

Solution

  • There are few issues in your code.

    1. Incorrect Syntax in if Statements

    2. There are no any default parameter values

    3. Variable Declaration. (When you are using croppedNmb inside a function you need to declare it.)

      function getFormat(textOrNumber) {

         if (textOrNumber === 0) {
      
           return cropped;
      
         } else if (textOrNumber === 1) {
      
           // Ensure croppedNmb is declared if used within this function
      
           let croppedNmb = formattedValue.replace(cropped, '');
      
           return croppedNmb;
         }
         // Optionally, handle the case where textOrNumber is neither 0 nor 1
         return null; 
       }
      
      
       // Assuming currentRange is defined elsewhere
       Logger.log(getFormat(1) + getFormat(0));