0

I have come across a jQuery/Javascript statement that I don't understand. It involves the "comma operator". I looked it up, but I don't see a good explanation with a good example.

Here is the statement:

var nav = $( '#site-navigation' ), button, menu;
Ken Shoufer
  • 1,393
  • 4
  • 10
  • 14
  • It's not the comma operator, but rather a part of the `var` statement syntax. The comma acts as a separator between separate variables being declared. (There *is* a comma operator, however; it's just that this isn't an example of the comma operator.) – Pointy Aug 21 '13 at 18:01
  • What do you exactly want to know? That's simply how the syntax of the variable declaration statement is. It works the way it does because the specification defines what it does. – Felix Kling Aug 21 '13 at 18:09

2 Answers2

4

This is not an operator. The comma allows you to define more than one variable with a single var statement:

var nav = $( '#site-navigation' ), // define variable 'nav' and assign $( '#site-navigation' ) to it
    button, // this defines variable named 'button' with no initial value 
    menu; // this defines variable named 'menu' with no initial value

The comma operator is something else - you can read about it here.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
  • In addition: your example defines 3 new vars in stead of one: nav, button and menu – Chris Visser Aug 21 '13 at 18:01
  • 2
    @Gumbo: This is not the comma operator, it's how the variable declaration statement is defined: http://es5.github.io/#x12.2. – Felix Kling Aug 21 '13 at 18:03
  • @Gumbo it is an operator, but it also servers a separate purpose in a `var` statement. This is not an example of the comma operator in action, in other words. – Pointy Aug 21 '13 at 18:03
  • @FelixKling You’re right, sorry, my fault. – Gumbo Aug 21 '13 at 18:04
2

Using the comma in that context:

var nav = $( '#site-navigation' ), button, menu;

is "shorthand" for...

var nav = $( '#site-navigation' );
var button;
var menu;
Duncan
  • 1,530
  • 15
  • 20