Error: Cannot read the property 'nota' of undefined. (Javascript)

Viewed 89

Can you help me with this error: "Cannot read the property 'nota' of undefined. "

const arrayN = [ 
    {nome: "Rapha", nota: 10},
    {nome: "Renan", nota: 8},
    {nome: "Stefani", nota: 12}
    ];

function maiorNota(alunos) {
    // Encontrando a maior nota no vetor turma.
    let maior = [];
    for (let i = 0; i < alunos.length; i++) {
        if (alunos[i].nota > alunos[i+1].nota || alunos[i].nota > maior) {
           maior =  alunos[i];
        }  
    } return maior;
}
const melhor = maiorNota(arrayN)

console.log(melhor)

3 Answers

Missleading Error

So the error is a bit missleading, but you should be aware when you do comparison with indice +1 because it could be that you try to access an element which is not existing.

In Java for example this would throw an index out of bounds exception which says more then "Cannot read property 'nota' of undefined".

Solution

If you would like to do a comparison with the next element then one solution is to update your condition in the for-loop and don't run to the end of the array instead run to the end-1 of the array.

In your last iteration step then you do the comparison with element at i with element at position i+1.

const arrayN = [{
    nome: "Rapha",
    nota: 10
  },
  {
    nome: "Renan",
    nota: 8
  },
  {
    nome: "Stefani",
    nota: 12
  }
];

function maiorNota(alunos) {
  // Encontrando a maior nota no vetor turma.
  let maior = [];
  for (let i = 0; i < alunos.length - 1; i++) {
    if (alunos[i].nota > alunos[i + 1].nota || alunos[i].nota > maior) {
      maior = alunos[i];
    }
  }
  return maior;
}
const melhor = maiorNota(arrayN)

console.log(melhor)

You reached an index that does not exist. You need to verify it exists.

const arrayN = [
    { nome: "Rapha", nota: 10 },
    { nome: "Renan", nota: 8 },
    { nome: "Stefani", nota: 12 }
];

function maiorNota(alunos) {
    // Encontrando a maior nota no vetor turma.
    let maior = [];
    for (let i = 0; i < alunos.length; i++) {
        if (alunos[i] && alunos[i].nota) > (alunos[i + 1] && alunos[i + 1].nota) || (alunos[i] && alunos[i].nota > maior) {
            maior = alunos[i];
        }
    } return maior;
}
const melhor = maiorNota(arrayN)

console.log(melhor)

When you get to last iteration i +1 is going to be 3, and there is no 3 index, so it is undefined.

Related