Search code examples
javascriptregexalgorithmvisual-web-developer

'SyntaxError: Invalid shorthand property initializer' when using regex


I'm trying to validate a pin using the following function

function validate(num){
  num.length === 4 || num.length === 6 ? {
    regex = /\d+/,
    regex:test(num)
  } 
  :
  false
}

however I'm getting this error and I can't figure out why

    /home/runner/index.js:3
    regex = /\d+/,
    ^^^^^^^^^^^^^

SyntaxError: Invalid shorthand property initializer

Solution

  • As others have pointed out, you can't put statements in conditional expressions (or any other expression, either), you can only put expressions.

    The error you're getting is because it thinks you're trying to write an object literal, but you can't have assignments inside object literals.

    You can use a normal if statement:

    if (num.length == 4 || num.length == 6) {
        var regex = /\d+/;
        return regex.test(num);
    } else {
        return false;
    }
    

    But there's no need for the conditional at all, you can test the length in the regexp itself.

    function validate(num) {
        return /^\d{4}$|^\d{6}$/.test(num);
    }