Search code examples
javascriptjqueryfrontendvariable-declarationweb-frontend

Writing a comma at the end of the first line of a multi-line variable declaration throws an error in Javascript


I wrote the following variable declarations in an application I'm working on

var $currentPage = $(".js-page") 
        $form = $("#new_location"),
        $body = $("body"),
        $submit = $form.find(".js-submit"),
        $elevationAngleKnob = $(".js-knob-elevation-angle"),
        $sunbathingTimeKnob = $(".js-knob-sunbathing-time"),
        $sunbathingStartKnob = $(".js-knob-sunbathing-start"),
        $sunbathingEndKnob = $(".js-knob-sunbathing-end"),
        $currentTimeKnob = $(".js-knob-current-time"),
        $nearestTimeKnob = $(".js-knob-nearest-time"),
        $editLocationForms = $(".edit_location");

If I don't end the first line of the declaration with a comma the code works just fine.

If I end the first line with a comma( as one might think is correct) then I get this strange error:

Uncaught ReferenceError: $elevationAngleKnob is not defined

What do you think is the problem?


Solution

  • I suspect you're trying to use $elevationAngleKnob in a different function from these variable declarations. When you put a comma at the end of the first line, all these variables are local variables, and you'll get an error if you try to access them in another function. Without the comma, automatic semicolon insertion changes this to:

    var $currentPage = $(".js-page");
    $form = $("#new_location"),
        $body = $("body"),
        $submit = $form.find(".js-submit"),
        $elevationAngleKnob = $(".js-knob-elevation-angle"),
        $sunbathingTimeKnob = $(".js-knob-sunbathing-time"),
        $sunbathingStartKnob = $(".js-knob-sunbathing-start"),
        $sunbathingEndKnob = $(".js-knob-sunbathing-end"),
        $currentTimeKnob = $(".js-knob-current-time"),
        $nearestTimeKnob = $(".js-knob-nearest-time"),
        $editLocationForms = $(".edit_location");
    

    This declares $currentPage as a local variable, and everything else is assignments to global variables, separated by the comma operator.