JavaScript Data structures part I, JavaScript Objects.

1.JavaScript Object.

An Object is a collection to properties, and a property is an association between a name (or key) and a value, every property has a unique key string that is unique within that object. 


Creating objects 

There are a lot of ways of creating JavaScript objects here i am going to discuss only three of them.
  • Using object constructor 
           var newObject = new Object();
  • Using Object prototype's create method
           var newObject = Object.create(null)//this will create an empty object since we passed null in it
  • Using bracket syntax sugar{}
         var newObject = {}//this also will create an empty object as well.


I.Getting properties from objects 
There are two ways of getting property values from objects;,one is through dot notation and the other is through square brackets. For example consider the following object.

var student = {
    "name":"justine",
    "age":32
}

a)Using dot notation.
console.log(student.name)//justine

b)Using the square brackets 
console.log(student['age'])

Square brackets are much more useful when the key name is a string with some other characters that makes it not qualified as a JavaScript literal  name for example a space

ie. console.log(student.second name)//this will print an error
but 
console.log(student['second name'])//this will not result to an error


II.Setting properties in objects 

As it is to getting properties values from objects there are also two ways of getting values from objects 

a)Using the dot notation 
student.surename = "peterson"
This will create a property with surename as key and peterson as the value
console.log(student['surename']) //if we run this to console will print peterson

b)Using the square bracket notation
student['course'] = "computer engineering"
console.log(student.course)//print computer engineering

III.Deleting properties in objects 


we can delete properties from objects by using the delete key word,for example;-
delete student.course;//this will delete the course property from the students 
or 
delete student['name']

Comments

Popular posts from this blog

Install Docker Engine - Community for Ubuntu

How to host a website locally in your own pc by using WAMP?