-3

I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on

var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
      ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets

}
console.log(ob);

OUTPUT IS


name:'at'
  • 3
    [JavaScript object basics - Learn web development | MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics) – Ele Mar 16 '19 at 16:25
  • Possible duplicate of [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Neil Locketz Mar 16 '19 at 16:28

3 Answers3

1

That is just the syntax for accessing or assigning properties of an object dynamically in javascript.

You can think of it as though you are doing: ob.name = 'at'.

Neil Locketz
  • 4,228
  • 1
  • 23
  • 34
0

Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.

The loop is getting each index value, and for each assign/create a new property using that index value.

That approach is a dynamically way of creating property-names in an object.

ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate

Read a little the docs here -> JavaScript object basics - Learn web development | MDN

Ele
  • 33,468
  • 7
  • 37
  • 75
0

There are two ways to access object properties in JavaScript

var person = {
  name: 'Jane'
}

person.name
// or
person['name'] 
// both return jane

in your case, that iterates through members of the array called ob2 first and only element of that array is a string name and it's given to that object as a prop, which becomes like following

ob['name'] = 'at';
// or
ob.name = 'at';

When to use brackets([]) over dot(.) If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets

Ertan Kara
  • 308
  • 3
  • 12