Quick Guide to JavaScript Objects – Hacker Noon

Simply put, an object is a nothing but collection of keys and corresponding values. Let’s take an example of my favorite character from Simpsons :

const obj = {
"name": "Homer Simpson",
"gender": "Male",
"children": ["Lisa","Bart"]//oops homer forgot the Maggie again DOH!
}

Now the question is how do you access the values? answer is as simple as it could be. Below is the output of various console logs :

console.log(obj.name)
>>"Homer Simpson"
console.log(obj.gender)
>> "Male"
console.log(obj.children)
>>["Lisa" , "Bart"]
console.log(obj.children[0])
>>"Lisa"

Essentially object.key will give you value of that key. You can also access the value of name by bracket notation:obj["name"] and it will give the same result as dot notation:obj.name.

Creating new object

There are many ways to create objects but sake of keeping this guide simple we are only going to discuss two ways to an create objects.

First is by just using curly bracket like shown above:

const obj = {
"name": "Homer Simpson",
"gender": "Male",
"children": ["Lisa", "Bart"]
}

Second is by using new keyword:

function Person(name,gender,children) {
this.name = name;
this.gender = gender;
this.children = children
}
const obj = new Person("Homer Simpson","Male",["Lisa","Bart"])

Adding new key :

Now let’s add new key to our object:

obj.wife = "Marge Simpson"
console.log(obj)

>> {

"name": "Homer Simpson",
"gender": "Male",
"contact no": "123456789012",
"children": ["Lisa", "Bart"],
"wife" : "Marge Simpson"
}

You can also set functions as values of any key. The name of key can be anything that is a string or that can be converted to string. We can also delete any key of objects using delete obj.key or delete obj["key"].

read original article here