Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I am getting undefined (reading 'name')?

I am expecting
"Lesson1"
"Lesson2"
.
.
.
"Lesson10",

but on console it is showing

Uncaught TypeError: Cannot read properties of undefined (reading
‘name’)
at app.js:14:26

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let myWork = [];

for(let i = 1; i <= 10; i++){

 let stat = i % 2 ? true : false;

 let temp ={
  name: `Lesson${i}`,
  status: stat   
 }

myWork.push(temp);

document.write(myWork[i].name+"<br>");
}

>Solution :

Its a simple issue, when you push to the array the position starts from 0, but your i starts from 1

See below.

let myWork = [];

for (let i = 0; i <= 10; i++) {

  let stat = i % 2 ? true : false;

  let temp = {
    name: `Lesson${i}`,
    status: stat
  }

  myWork.push(temp);

  document.write(myWork[i].name + "<br>");
}

If you want to start from Lesson1 try this

let myWork = [];

for (let i = 1; i <= 10; i++) {

  let stat = i % 2 ? true : false;

  let temp = {
    name: `Lesson${i}`,
    status: stat
  }

  myWork.push(temp);

  document.write(myWork[i - 1].name + "<br>");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading