Home > Net >  Syntax error when trying to run code from VS Code terminal
Syntax error when trying to run code from VS Code terminal

Time:10-16

I'm trying to run some code in my VS Code terminal and when I click on Run active file I get this syntax error message

line 5: syntax error near unexpected token `('
line 5: `const addTwoNums = (numbers, k) => {'

This is the code I'm trying to run so I know there isn't a syntax error. If I try and run the same function in my browser console it works correctly. I'm running VSCode on a Mac.

const addTwoNums = (numbers, k) => {
    let left = 0;
    let right = numbers.length - 1;

    while (left < right) {
        const sum = numbers[left]   numbers[right];
        if (sum === k) {
            return true;
        } else if (left < k) {
            left  = 1;
        } else {
            right -= 1;
        }
    }
    return false;
}

addTwoNums([10, 15, 3, 7], 17);

CodePudding user response:

Add this line to the top of the file:

#!/usr/bin/env node

This tells the shell to run the script with node.

  • Related