Learn Creating And Accessing JavaScript Object Properties

Let's first create a JavaScript object and attach some properties to it.
  1. 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.
  1. student.age = 30;  
  2. //or  
  3. student["age"] = 30;  
To access any of them, we can use either approach.
  1. document.write(student.age);  
  2. 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.
  1. student["Last Name"] = "Mor"//will work  
  2. 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!