Tuesday 12 February 2013

JavaScript - Predict the Output - Question 3


"use strict";

var employee = {
    name: 'Amnal'
};

Object.defineProperty(employee, 'age', {
    value: 28,
});

for(var x in employee)
{
    console.log(employee[x]);
}

"use strict";
var employee = {
    name: 'Amnal'
};

Object.defineProperty(employee, 'age', {
    value: 28,
});

for(var x in employee)
{
    console.log(employee[x]);
}

7 comments:

  1. Strange!

    My prediction was Amnal and 28.

    employee['name'] and employee['age'] outputs Amnal and 28 respectively while in a loop only Amnal shows up.

    ReplyDelete
  2. Looks like you're going to get an object output to the browser console of choice that looks somewhat like this:

    Employee = {
    name: 'Amnal'
    age {
    value: 28
    }
    }

    You can reference employee.name and employee.age.value

    ReplyDelete
  3. Actually, nothing will work as you have a Comma in there that is extra. "value: 28," should be "value: 28".

    ReplyDelete
  4. You will only get the property name. Assuming you fix the comma typo. When using Object.defineProperty creates a property that is not enumerable. To make it enumerable you need to do:

    Object.defineProperty(employee, 'age', {
    value: 28, enumerable: true
    });

    ReplyDelete
  5. Jeremy and Marko, I have run the code with "value: 28,", it works fine in Firebug. Though, ',' should be removed.

    Output is "Amnal".

    By default defineProperty have enumerable, writable and configurable property set as false and due to which it cannot be modified or enumerated. Thus, new property added through defineProperty will never show up in for loop until the enumerable flag has been set to true;

    ReplyDelete
  6. Reference: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty

    ReplyDelete