Search code examples
javascriptcompiler-errorsautomatic-semicolon-insertion

Error in omitting semicolon - can someone explain why?


Can someone please explain why if I omit the semicolon in the line while(nums[right-1] == nums[right--]);that I get a syntax error? I generally understand the point of semicolons, but why this specific line and not the others?

var threeSum = function(nums) {
    nums.sort((a,b)=>a-b);
    let result = [];
    for (let i=0;i<nums.length;i++) {
        let t = -nums[i];
        let left = i+1, right = nums.length-1;
        while(left < right) {
            if (nums[left] + nums[right] == t) {
                result.push([nums[i], nums[left], nums[right]]);
                while(nums[left+1] == nums[left++]);
                while(nums[right-1] == nums[right--]);
            } else if (nums[left]+nums[right] < t) left++;
            else right--;
        }
        while(nums[i+1]==nums[i]) i++
    }

    return result;

};

Solution

  • A loop needs something to loop over. Basically either a statement or a code block. For example:

    while (something) {
      this.isInACodeBlock();
    }
    

    or:

    while (something)
      this.isAStatement();
    

    Keep in mind that a statement can be a no-op. A semicolon by itself serves that purpose. And since carriage returns don't matter to the language, this is a loop with a statement:

    while (something);
    

    Taking a step out, this loop is within a code block, which ends right after the loop:

    if (somethingElse) {
      while (something)
    }
    

    If there was just a statement following the while loop then it would be syntactically correct, even if the behavior is unexpected or a bug. But there's a closing curly brace.

    So the interpreter is expecting either a statement or an opening block, but it's encountering a closing block. Which is an error.