Objects in JavaScript are used to store keyed collection of various data and more complex entities.
An object can be created with {..} with an optional list of properties. A property is a “key: value” pair, where key is a string(also called as property name) and value can be anything.
An empty object can be created using one of the two methods
let user=new Object(); //object constructor syntax
let user={}; // object literal syntax
We can immediately put some properties into {...} as “key: value” pairs:
let user={
name:"vinod",
age:30
};
A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.
In the user object, there are two properties:
- The first property has the name
"name"and the value"vinod". - The second one has the name
"age"and the value30.
Property values are accessible using the dot notation:
// get property values of the object:
alert( user.name ); // vinod
alert( user.age ); // 30
The value can be of any type. Let’s add a boolean one:
user.isAdmin = true;
To remove a property, we can use the delete operator:
delete user.age;
We can also use multiword property names, but then they must be quoted:
let user = {
name: "vinod",
age: 30,
"likes birds": true // multiword property name must be quoted
};
For multiword properties, the dot access doesn’t work:
// this would give a syntax error
user.likes birds = true
JavaScript doesn’t understand that. It thinks that we address user.likes, and then gives a syntax error when comes across unexpected birds.
The dot requires the key to be a valid variable identifier. That implies: contains no spaces, doesn’t start with a digit and doesn’t include special characters ($ and _ are allowed).
There’s an alternative “square bracket notation” that works with any string:
let user = {};
// set
user["likes birds"] = true;
// get
alert(user["likes birds"]); // true
// delete
delete user["likes birds"];