Quick Guide to JavaScript Objects

Forex stock trading

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 :

>>"Homer Simpson"
>> "Male"
>>["Lisa" , "Bart"]

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"

>> {
"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”].

Enumerate the keys of an object :

If you don’t know the keys and you want to access the objects then you can iterate through keys using object.keys(obj) . object.keys(obj) will give you array of keys and then you can call forEach() and iterate through key. below is the example of that

Object.keys(data).forEach( (element) => {
output : 
>>"Homer Simpson"
>>"Marge Simpson"

That’s all folks!!!

Here is some random programming humor to cheer up your day

Quick Guide to JavaScript Objects was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

Read about withdrawable no deposit bonus and make profit trading now