0

I cannot understand the following code, var formData = {}; I guess defines a object "formData", but why to save each element in the formdata["fullName"]? What is this with []? Isn't it used for array? i confused. Could somebody explain this code? Thank you!

function readFormData(){
    var formData = {}; 
    formdata["fullName"] = document.getElementById("fullName").value;
    formdata["empID"] = document.getElementById("empID").value;
    formdata["salary"] = document.getElementById("salary").value;
    formdata["city"] = document.getElementById("city").value;
    return formData;
}
Eddie
  • 26,593
  • 6
  • 36
  • 58
Zi Sang
  • 69
  • 1
  • 9
  • 1
    It's one of access methods. Same as `formData.fullName`. Consistency maybe? You can use `[]` or `.` for accessing object properties – Justinas May 25 '19 at 13:55
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Accessing_properties – arieljuod May 25 '19 at 13:56
  • 1
    `[]` is a property access called bracket notation. Its used when we need to access properties dynamically. By the way arrays in javascript are also objects. – Maheer Ali May 25 '19 at 13:58
  • Also, there a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) constructor which takes the form element as a parameter and creates a key-value pair of all the inputs in the form. `var formData = new FormData(document.getElementById("yourFormId"))` – adiga May 25 '19 at 14:28
  • @LGSon oh, right I did not consider that, apologies. – Jonas Wilms May 25 '19 at 14:33

1 Answers1

4

In javascript, array keys are defined and referenced with square brackets. Object properties can be defined an accessed the same way or with dot notation.

In your case you do have an object, and it's properties can be accessed using bracket notation.

The following two lines are thus equal:

  obj["property"] = value;
  obj.property = value;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Scott Flodin
  • 320
  • 1
  • 5