1

I've seen two ways to use objects, I would like to know what's the difference or it's just different syntax?

Option 1

body(data) = {
    item1: data.val1;
    item2: data.val2;
    item3: data.val3;
}

Option 2

body(data) = {
    item1 = data.val1,
    item2 = data.val2,
    item3 = data.val3
}

body.item1 = '';
body['item2'] = '';
Dangur
  • 139
  • 1
  • 7
  • The first example is creating a JSON object, although it should have ',' NOT ';' after each member. The second isn't valid either. – SPlatten Nov 23 '18 at 10:09
  • Are you talking about defining the object or accessing the object? Your option 1 is not valid JS, which you can see by running it anywhere. Neither is the second one though. I have to wonder, where exactly have you seen these used? – Roope Nov 23 '18 at 10:09

2 Answers2

1

In your example there is no difference, but the array-like syntax will help you once you need to use a variable as the object property, let's say:

const foo={}
const prop= 'item4';

foo[prop] = 'something good'

alert(foo.item4)//Should alert "something good"
i.brod
  • 3,993
  • 11
  • 38
  • 74
0

There is no difference, you can access properties on Objects via the dot notation or the square brackets notation. To be compliant to the coding standards (and on the why the brackets notation is useful) you should always use the dot notation to reference to properties; the only case in which you should be using the square brackets notation is when you want to reference to a property that is not hard coded but will be referenced at run time. (I.E. when you use a variable to know which property to get).

Alpe89
  • 299
  • 2
  • 11