-1

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

Zaid Mirza
  • 3,540
  • 2
  • 24
  • 40
  • 1
    in your second case,you are trying to get the value of FirstName from an undefined object. – Sudharsan Selvaraj Sep 21 '16 at 10:27
  • Your array contains 3 elements, and you want to access 5th (6th taking in mind that array count starts with 0) element that is not present? – Khallister Sep 21 '16 at 10:28
  • @Khallister names[5] and names[5].FirstName both are not defined. names[5] returns 'undefined' but names[5].FirstName error. thats my point – Zaid Mirza Sep 21 '16 at 10:32

4 Answers4

1

Because your for iteration does not reach the sixth (counting zero) index, but only the third.

What you are doing inside the for (var i = 0; i < 3; i++) is essentially:

names.push({FirstName:'abc',LastName:'zyx'});
names.push({FirstName:'abc',LastName:'zyx'});
names.push({FirstName:'abc',LastName:'zyx'});

The result of the iteration would be this:

console.log(names[0].FirstName); // "abc"
console.log(names[1].FirstName); // "abc"
console.log(names[2].FirstName); // "abc"
console.log(names[3].FirstName); // undefined
console.log(names[4].FirstName); // undefined
console.log(names[5].FirstName); // undefined

By doing console.log(names[5]) you are outputting the fifth index's content of the names variable. undefined in javascript is not necessarily an error message.

names[5]
     ^^^ undefined

By doing console.log(names[5].FirstName) instead, you are trying to access a property of an object that does not exist, since names[5] is undefined.

names[5].FirstName
     ^^^ undefined
GiamPy
  • 3,543
  • 3
  • 30
  • 51
  • I know that, but im confsuing why it dont gives error on line names[5]? It was also not exist. I want same behavior in names[5].FirstName if it is not defined – Zaid Mirza Sep 21 '16 at 10:29
  • Because by doing `console.log(names[5])` you are outputting the fifth index's content of the `names` variable. `undefined` in javascript is not necessarily an *error* message. By doing `console.log(names[5].FirstName)` instead, you are trying to access a property of an object that does not exist, since `names[5]` is `undefined`. – GiamPy Sep 21 '16 at 10:33
  • yes you got my point, so whats the solution of it. i want `names[5].FirstName` not to give error it should just return undefined – Zaid Mirza Sep 21 '16 at 10:36
  • Then just initialize an empty object in `names[5]` by doing `names[5] = {};`. You can't do that in other ways. – GiamPy Sep 21 '16 at 10:38
  • I have updated my Question,see for loop, now names array length is dependant on userInput. So I cant predefine length – Zaid Mirza Sep 21 '16 at 14:00
  • Try using `try/catch` then like Anurag uses in [this example](http://stackoverflow.com/a/2666816/2362433). – GiamPy Sep 21 '16 at 14:03
1

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.

Samundra
  • 1,869
  • 17
  • 28
  • My array is populating dynamically in actual code. I want a workaround if a user tried to access undefined property then just notify, dont give error just like names[5]. – Zaid Mirza Sep 21 '16 at 10:38
  • Then you have to check if the property exists or not in the object. Please update your question with this information. Also see [Find javascript object has property or not](http://stackoverflow.com/questions/1894792/how-to-determine-whether-an-object-has-a-given-property-in-javascript) this will give you more concept. – Samundra Sep 21 '16 at 10:41
  • I have updated my answer to address your comment. Please check the answer and let us know whether it works for you or not. If you still feel confused then please update your question accordingly and we'll try to address it. – Samundra Sep 21 '16 at 10:49
  • I have tried this `names[5].hasOwnProperty('lastName')`.It gives me error that cannot ready property `hasOwnProperty`. its taking that function as property – Zaid Mirza Sep 21 '16 at 13:56
  • how we can test this for object which does not exist. – Zaid Mirza Sep 21 '16 at 14:02
  • Can you share with us the code that you are using? We'll then be able to share our thoughts with you. – Samundra Sep 21 '16 at 17:14
  • Thanks @Samundra , I was checking hasownProperty on the Object which does not exist. Now my problem is fixed with it – Zaid Mirza Sep 22 '16 at 05:30
0

Your array has three elements. Your trying to access the sixth element which in your above code will not exist.

Stewart
  • 3,023
  • 2
  • 24
  • 40
0

For the first part of your question, you have created an array having 3 elements i.e var names=['a','b','c']; and you are trying to access 6th element from your defined array names[5], which not really exist. Hence it's returning undefined.

For the second part of your question you have following codes:

var names=[];

for(var i=0;i<3;i++)
{
  names.push({FirstName:'abc',LastName:'zyx'});
}

So above piece of codes create names array having 3 element and each one is an object. So you have to access it like names[0].FirstName. But you are trying to access names[5].FirstName, where 6th elements in names array is not really exist.

Hope this will help you!

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37