Wednesday, 20 July 2016

Javascript object property

You have 2 ways to declare a new object. The first way is to using a shorthand declaration while the second way is to declare a new object in the same way like other programming language.

    var o = {};

OR

   var o = new Object();

Unlike other strong typed programming language such as C# or C++, Javascript allows you adding new property at anytime.

For example, adding name and age properties to an object instance:

    o.name = 'John';
    o.age = 18;
    o.savings = 2100;
    console.log(o);

You are allowed to remove any property as well:

    delete o.savings;
    console.log(o);

To retrieve all property names from an object, you need to call Object.keys() function which returns an array of string:

  var properties = Object.keys(o);
  console.log(properties);

Let says, you want to access the property value without knowing the property name:

    var age_of_the_person = o[properties[1]];

But, you can't access the property value by index:

    var not_working = o[1];

    console.log(not_working);

No comments:

Post a Comment

We are moving

We are moving this blog to our new blog site: https://ciysys.com/blog/nodejs.htm