DEV Community

Cover image for Javascript Object #2
Asir-Sam
Asir-Sam

Posted on

Javascript Object #2

From the last post we've seen what is Object in Javascript and how it is created using the Object literal Notation and how strong object is,what he is capable of,that's fine.

Have you ever had a thought,Yeah wow! How Good we created a Object but wonder how can we use those Properties inside the Object and Can we delete or replace those property value.Yes we can Do that,and we are going to see that in this Post.

To access the Object properties we do have two Global methods,

  1. Dot notation

  2. Array like notation

Dot notation

The following illustrates how to use the dot notation to access a property of an object:

`objectName.propertyName`
Enter fullscreen mode Exit fullscreen mode

for Example

`let objectName = {
firstName: 'SAM',
lastName: 'r',
}`
Enter fullscreen mode Exit fullscreen mode

here we can access the firstName property by,

objectName.firstName
objectName.lastName

Enter fullscreen mode Exit fullscreen mode

Array like notation

The following illustrates how to access the value of an object’s property via the array-like notation:

`objectName['propertyName']`
Enter fullscreen mode Exit fullscreen mode

here we can access object items by,

`objectName['firstName']`
`objectName['lastName']`
Enter fullscreen mode Exit fullscreen mode

as for now we have seen two methods,which is the best method to access those property is,i would say array like notation.And i have a major reason for this,which we will discuss now.

From the above two methods Dot looks very simple but there is big drawback in this method,and i will explain it with an example,

Consider an Object we have with a property name 'The Object',while we try to access this property value using dot notation.we will get an error 'undefined'.Javascript will take the property name as 'The' and search for it,and thus it results in undefined.

So the Best way is to use the Array like Notation.That's it for now.We will learn more about Object in Upcoming Posts

Many thanks ...
Sam

Top comments (0)