1

I have the following question : in Node/Javascript why this function declaration is wrong inside an object or a class??

var obj = {
  function x() {
    /* code */
  },
  bar: function() {
    /* code */
  }
};

the first function declaration x() cause

  function x() {
           ^

SyntaxError: Unexpected identifier

i don't understand why i can't use the function keyword inside an object or a class , what difference does it make when using function x() or just x(), just x() works fine , but adding function keyword in front of it - cause the above problem. why ?

1

2 Answers 2

3

You need to assign a key in Javascript to their objects, the second one works because you have a key assigned to it that is bar, in the first one not. Try adding the key before the function declaration,like this:

var obj = {
  foo:function x() {
    /* code */
  },
  bar: function() {
    /* code */
  }
};
Sign up to request clarification or add additional context in comments.

Comments

2

in Node/Javascript why this function declaration is wrong inside an object or a class??

Of course it's wrong, in JavaScript an object is pairs of key/values, separated with comma. With your code, you are breaking this syntax, because you are not declaring a property in your case, you need to specify the key before writing function x().

If you refer to MDN Object initializer reference you can see that:

An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

And if you check the New notations in ECMAScript 2015 section of Docs you will see the difference between writing function x(), x() or just x().

And according to the docs these are possible Method definitions syntaxes:

var o = {
  property: function (parameters) {},
  get property() {},
  set property(value) {}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.