Instances of Object are used to store data.
There are two ways to create an instance of Object.
The first is to use the new operator with the Object constructor:
let person = new Object(); person.name = "HTML"; person.age = 29;
The other way is to use object literal notation.
For example, the following defines the same person object from the previous example using object literal notation:
let person = { name: "HTML", age: 29 };
Property names can be specified as strings or numbers when using object literal notation:
let person = { "name": "HTML", "age": 29, 5: true };
It's also possible to create an object with only the default properties and methods using object literal notation:
let person = {}; // same as new Object() person.name = "HTML"; person.age = 29;
The object literals is a preferred way of passing a large number of optional arguments to a function:
function displayInfo(args) { let output = ""; if (typeof args.name == "string") { output += "Name: " + args.name + "\n"; }//from w w w .ja v a 2 s. com if (typeof args.age == "number") { output += "Age: " + args.age + "\n"; } console.log(output); } displayInfo({ name: "HTML", age: 29 }); displayInfo({ name: "Javascript" });
We can access properties via bracket notation.
console.log(person["name"]); // "HTML" console.log(person.name); // "HTML"
The bracket notation allows you to use variables for property access:
let propertyName = "name"; console.log(person[propertyName]); // "HTML"
You can use bracket notation when the property name contains characters:
person["first name"] = "HTML";