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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Hiteshdua1
  • 2,126
  • 18
  • 29

2 Answers2

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");
  }
}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 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. –  May 25 '16 at 06:58
  • 1
    "*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. – mferly May 25 '16 at 15:36
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.

Webdev
  • 617
  • 6
  • 24