Creating And Accessing JavaScript Object Properties

In this article, we will learn about creating and accessing JavaScript object properties.

Let’s first create a JavaScript object and attach some properties to it.

var student = {name : 'Ajay', rollno : 1};  

As we can see, we have created an object and attached two properties.

If we want to attach some more properties, then we can simply go ahead and do it using Dot (.) notation and Bracket Notation as given below.

student.age = 30;  
//or  
student["age"] = 30;  

 To access any of them, we can use either approach.

document.write(student.age);  
ocument.write(student["age"]);  

Now, the obvious question that comes to my mind is if both approaches produce identical results, then why did introduce two ways to do the same work?

Well, I found that bracket notation can be very useful in a few cases given below

If we, for some reason, needed to create a property on an object using a property name, that is not a valid identifier.

student["Last Name"] = "Mor"; //will work  
student.Last Name = "Mor" //won't work  

You may still be wondering why we might ever do this.

Well, what if we wanted to create an object out of values being provided/entered by an end user?

Or it’s possible we have a source of JSON data that has property names that are not valid identifiers.

It’s not too common that we run into this, and we should always use valid identifiers for our property names for simplicity, but it is good to know about such exceptional cases if we need it.

If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend or sharing it on Twitter or Facebook. Thank you!

LEAVE A REPLY

Please enter your comment!
Please enter your name here