eveo
eveo

Reputation: 2833

Commas in Javascript

<script>

(function() {

$('html').addClass('js');

var contactForm = {

    container: $('#contact'),          <-- THIS COMMA

    init: function() {
        $('<button></button>', {
            text: 'Contact Me'
        })
            .insertAfter('article:first')
            .on('click', this.show);
    },  <---------------------------------- AND THIS COMMA

    show: function() {
        contactForm.container.show();
    }
};

contactForm.init();

})();

</script>

In the above script, I noticed:

container: $('#contact'),

Is that one way to declare a variable? Doing the following breaks the script:

var container = $('#contact');

Also, what is with the commas after the init function and the container variable (if it is a variable)?

Upvotes: 3

Views: 292

Answers (5)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

Those are key:value pairs of the object contactForm you defined separated by commans

var obj = { key1 : value1, 

            key2 : value2

            method1 : function(){
              // definition
            },
            method2 : function(){
              // definition
            }
}

The thing that confused me in my early days is that what is function(){....} doing inside a variable(in this case an object) definition until I discovered functions are objects too in js which may not be the same case in language you have used earlier .

and this function function(){....} without name is called a anonymous function.

Here's a good thread on anonymous function Why do you need to invoke an anonymous function on the same line?

Upvotes: 1

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

That block of code (beginning with var contactForm = {) is declaring an object using object literal notation. Commas separate the different key-value pairs in the object literal notation.

var obj = { key1: value1, key2: value2 };

Upvotes: 3

VisioN
VisioN

Reputation: 145398

This way you declare an object:

var contactForm = {
    // properties:
    property1 : value,
    property2 : value,
    property3 : value,

    // methods:
    method1 : function() {
        // ...
    },
    method2 : function() {
        // ...
    }
};

You can find more information about JavaScript objects in MDN ...and in the comments below :)

Upvotes: 8

S P
S P

Reputation: 4643

That is called Object literal notation.

Which is basically a Comma-Separated list of name/value pairs, wrapped in curly braces.

Advantage of this notation is that all data within the braces are encapsulated and not defined globally which avoids conflicts with other scripts or libraries.

Upvotes: 1

kinakuta
kinakuta

Reputation: 9037

Commas are used to separate name/value pairs when defining objects:

var newObj = {
  name: value,
  another_name: another_value
};

Upvotes: 2

Related Questions