0

Let's say we need to add a property to an existing js object

var billingData = {}

In my case, I want to store input value in the js object
Here's the basic input

<input type="text" class="form-control" id="billingFullName">

We, basically, have two ways to add the property to the js object:
The first one:

billingData["billingFullName"] = document.getElementById('billingFullName').value

And the second one:

billingData.billingFullName = document.getElementById('billingFullName').value

What's the difference between them?

I'm asking, because when I was submitting the js object using AJAX to MVC Controller, where properties where added using the [] notation, the model in the Controller appeared to be null. Whereas, the dot notation appeared to solve the issue and I'm wondering why..

Masudur Rahman
  • 1,585
  • 8
  • 16
saw13
  • 61
  • 1
  • 6
  • There is no difference if you are using these strings.. Bracket notation is if you want to use a variable as the property name or you have a property name that will not be syntactically correct as dot notation, e.g., if there is a space of a plus sign, for example. – VLAZ Oct 27 '19 at 16:34

1 Answers1

0

Typically you use bracket notation when you need to define a property dynamically such as with a variable or if the key is not in proper format for dot notation:

const obj = {}
const someKey = 'key'
obj[someKey] = 'somevalue'

console.log(obj.key) // 'somevalue' 
console.log(obj.someKey) // undefined 

Dot notation is when you already know the key:

const obj = {}
object.key = 'someValue'
Willman.Codes
  • 1,352
  • 1
  • 5
  • 13