0

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?

user3790827
  • 695
  • 1
  • 8
  • 17
  • 1
    I can't think of a reason for that. Can you make a [stack snippet](http://meta.stackoverflow.com/questions/270944/feedback-requested-stack-snippets-2-0) with the HTML and code to demonstrate the problem? – Barmar Jul 28 '15 at 00:36
  • 1
    Can you show more of the code? Is the use of `$elevationAngleKnob` in the same function as all these declarations? – Barmar Jul 28 '15 at 00:37
  • With firstline ending with comma, runs perfectly fine. Check this http://jsfiddle.net/passionintellectual/hgse340w/ – Ganesh Nemade Jul 28 '15 at 00:38
  • If you leave off the comma automatic semi-colon insertion will terminate your variable declaration at the first line. Then you create a load of global variables. So no, your code isn't fine. Please heed the error message. – 1983 Jul 28 '15 at 00:39

1 Answers1

4

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612