2

The only difference between these two pieces of code are in line 1 in both blockquotes.

Why do these two pieces of code behave different?

function cat.meow() {
    console.log("Meow");
};

versus

cat.meow = function () {
    console.log("Meow");
};
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
gzaw
  • 125
  • 1
  • 6

2 Answers2

6

The first one is invalid JavaScript, the second is a better idea, more details in the following...

Why?

Variable / Function names can only have Letters, Underscores, $, Numbers (if they're not the first character) along with a few other ACII, and unicode characters (check here or here as recommended by Kaiido and Felix King). It would be the same as var cat.meow; which is invalid JavaScript and will throw an error. More specifically

SyntaxError: Unexpected token '.'.

The compiler is expecting a parenthesis or a space but it sees a period not assuming it is an object. This also happens with bracket syntax for an object :( which means you can't define a function for an object 'item' the first way

Explanation

When you do: foo = function () {} it set the value of foo to the function. When you do it as a function function foo () {} it 'creates' foo.

So...

The second one is referring to meow in cat. So it is setting meow in cat to the function which is valid. That is equivalent to this:

var cat = {
    meow: function () {
        console.log("Meow!");
    }
};

Obviously is cat isn't defined, this will still throw an error. If you really really want to have your function to be called cat.meow (I would strongly advise against it), you would do the following

window['cat.meow'] = function () {
    console.log("Meow");
};

This clutters the global scope unless you have a different object and is extremely bad practice; so if you do use it, do it in secret otherwise almost every programmer will be bashing you on your coding practices.

Community
  • 1
  • 1
Downgoat
  • 13,771
  • 5
  • 46
  • 69
  • *"along with a few other ACII characters"* Actually, unicode letters are allowed as well as you can see in the question you linked to). – Felix Kling Apr 07 '15 at 04:16
3

Have you at least tried it? The first one isn't a valid javascript. It should produce

Uncaught SyntaxError: Unexpected token .

The second one is valid. In that context, cat is an object and you're creating a meow method for it.

The error suggests what that . is not a valid identifier. In javascript, and most languages, anything which matches the regex \w+, meaning alphanumerical characters + underscore, is a valid identifier.

And in most languages, including javascript, it is also mandatory to have the identifier begin with an alphabet or underscore. In javascript however, $ is also a valid identifier.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95