Zaid Mirza Zaid Mirza - 1 month ago 10
Javascript Question

JavaScript array with property

I was using array like this

var names=['a','b','c'];


when I tried to access
names[5]
. it returns undefined simply,gives no error.

After that I changed my array like this

var names=[];

for(var i=0;i<inputNumberByUser;i++) //guys my array is populating dynamically,depends upon user input
{
names.push({FirstName:'abc',LastName:'zyx'});
}


When I tried below code, it gives me error that, Could not read FirstName of undefined

names[5].FirstName;


why above line is giving error? it should just return undefined as normal array

names[5]
and
names[5].FirstName
both are not defined.
names[5]
returns
'undefined'
but
names[5].FirstName
error. thats my point.
names[5].FirstName
should also simply return
'undefined'
as
names[5]
did

Answer

Why you are getting error?

Here names[5] returns undefined and you are trying to access FirstName property of undefined element. It's like trying to get address of someone who doesn't exists.

And You also have error in line for(var i=i<3;i++) may be you wanted to write for(var i=0; i<3; i++)

Possible Solution

If you are looking to push to names array then you should do something like below:

var names=[];

// Push objects to names
for (var i = 0; i < 3; i+=1) {
    names[i] = {
        firstName: 'Name: ' + i
    }

    // Lastname defined only for 2 index object
    if (i === 2) {
        names[i].lastName = 'Lastname only on 2';
    }
}


for (var i = 0; i < 3; i+=1) {
    // outputs names[i]
    console.log(names[i]);

    // Check whether lastName property exists on the element or not    
    if (!names[i].hasOwnProperty('lastName')) {
        console.log('no lastName property defined');
    }
}

Here we are creating object and assigning to names[i]. Remember, i is incrementing so each time we'll be assigning objects to new position.

Then in second loop, I am just referencing to those previously assigned values and checking whether they have lastName property defined on them or not.

If you are still confused let us know and we'll try to help you.