Undefined instead of ReferenceError

Hi,

Can anybody kindly explain why in the case below I am getting Undefined? I expected to get kind of error (Reference Error possibly) as I am accessing variable that is inside the function (i.e. local variable) but nothing is printed on the console apart from undefined.

var customer = function () {
    var name = 'customer_1';
    return { 
        getName: function () {
            return name;
        },
        setName: function (newName) {
            name = newName;
        }
    }
} () 
console.log(customer.name);

I think, though I’m not certain, the reason you’re getting undefined and not an error is because the object customer exists - it’s the first thing you define.

I don’t think the function-scoped variable name is accessible as customer.name, though, so JS thinks you’re trying to access an undefined object property and so that’s why you’re getting that back.

Not an expert with JS, though, so could be wrong…

The reason your getting undefined is because your returning a object with two different methods. As far as i can i see .name is not a property of the returned or defined anywhere in the object which is why it’s possible you’re getting undefined.
I noticed your also calling the function before logging to console which is going to immediately return either methods you decide to call. You’re best bet is performing console.log(customer.getName()) which will get the name of the customer.

You can also `

var customer = function () {
var name = ‘customer_1’;
return {
name ,
setName: function (newName) {
name = newName;
}
}
} ()
console.log(customer.name);`

which make a it the the name variable a property of the object is which you can perform console.log(customer.name). Hoped that helped.

1 Like