4

When i type this code in javascript console, this does not through an error, instead it runs.

var a = { 
  b:"123",
  update(){
     console.log("hello");
  }
}

The problem is, update() does not have a function keyword and when i check the properties of object a , i get :

b: "123"
update: function ()
__proto__: Object

What is javascript actually doing here?

1
  • 2
    ^^^^^ but only in es6 Commented May 25, 2016 at 6:44

2 Answers 2

5

In ECMA Script 6, you can define properties of an Object during its creation, without the :.

For example,

var data = 100;
var a = { data };
console.log(a);
// { data: 100 }

Similarly, in your case, you are creating two properties, one is called b and another one is called update, where b is 100 and update is actually a function object called update.

Read more about it here


Note: This is just the shorthand notation introduced in ECMA Script 6. You can still use the ECMA Script 5 way of creating properties which are functions, like this

var a = {
  b: "123",
  update: function update() {
     console.log("hello");
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, to be precise, there are two types of shorthand object literal notation; one is called shorthand property names, the other shorthand method names, and they are relatively distinct. The latter is what the OP is wondering about.
"In ECMA Script 6, you can define properties of an Object during its creation, without the :" Must be noted that the name/value must be identical. In this case data within var a = { data }; will search (within scope) for a variable also named data. You obviously know this, but I thought it should be pointed out for future visitors so they know what's actually going on here.
0

The syntax to create a javascript object is :

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

Here fullnme is a method of the object and can be accessed using:-

person.fullname()

Because of () in your code

var a = { 
  b:"123",
  update(){
     console.log("hello");
  }
}

Javascript is understanding it as a function . Hope this explanation helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.