Search code examples
javascriptsyntax-error

Why error "unexpected token" in first line of function definition?


Why do I get an error saying "Unexpected token" at the first line of the following code that defines the function calcTotal?

calcTotal: function(type) {
    sum = 0;
    data.allItems[type].forEach(function(cur) {
        sum = sum += cur.value();
    })
    data.totals[type] = data.totals[type] + sum;
}

Solution

  • Function statements require a function name. So this is not a valid statement:

    calcTotal: function(type) { }
    

    It is still OK to prefix a statement with calcTotal:, but that defines a label, not the name of the function. The function keyword, when it is used at the start of a statement (whether labeled or not), must be followed by its name.

    You probably did not intend to define a label, but a function called calcTotal, and that should be written as follows:

    function calcTotal(type) { }
    

    or, you can also assign a function expression to a variable, like so:

    var calcTotal = function(type) { }
    

    Note that in other contexts your syntax could be correct. This would be when inside an object literal, defining an object property:

    const myObj = {
        calcTotal: function(type) {
        }
    }
    

    This defines myObj.calcTotal as a function. Here calcTotal is not a label, but an object property name, and what follows it is not a function statement, but a function expression. See also var functionName = function() {} vs function functionName() {} for a comparison of these two concepts.