-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

3
  • 1
    in your second case,you are trying to get the value of FirstName from an undefined object. Commented Sep 21, 2016 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? Commented Sep 21, 2016 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 Commented Sep 21, 2016 at 10:32

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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].
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 this will give you more concept.
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.
I have tried this names[5].hasOwnProperty('lastName').It gives me error that cannot ready property hasOwnProperty. its taking that function as property
how we can test this for object which does not exist.
|
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

6 Comments

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
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.
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
Then just initialize an empty object in names[5] by doing names[5] = {};. You can't do that in other ways.
I have updated my Question,see for loop, now names array length is dependant on userInput. So I cant predefine length
|
0

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

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.