Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
Multiple conditions in while loop doesn't work

We have an array of objects representing different people in our contacts lists. We have a lookUpProfile function that takes name as an argument. The function should check if name is an actual contact's firstName. It will print the contact name's on the console, followed by true if the name matches the contact's firstName, otherwise, it will print false.

I want my while loop to traverse the array until either nameCheck equals true OR i got bigger than contact length (aka it reaches the end of the array).

It seemed like both of the conditions in my while loop (nameCheck == false || i < contacts.length) are not working. For some reason even when namecheck equals true and i got bigger than contact length, the while loop keeps executing.

I know you can achieve the same result with a for loop instead and I had done that. But for the sake of learning, I would like to know why my while loop doesn't work.

Thank you so so much in advance.

const contacts = [
  {
    firstName: "Akira",
    lastName: "Laine",
    likes: ["Pizza", "Coding", "Brownie Points"],
  },
  {
    firstName: "Harry",
    lastName: "Potter",
    likes: ["Hogwarts", "Magic", "Hagrid"],
  },
  {
    firstName: "Sherlock",
    lastName: "Holmes",
    likes: ["Intriguing Cases", "Violin"],
  },
];

function lookUpProfile(name) {
  var nameCheck = false;
  console.log(nameCheck);
  
  var i= 0;
  console.log (i);

  while (nameCheck == false || i < contacts.length){
    var nameOnContacts = contacts[i].firstName;
    console.log(nameOnContacts);
    nameCheck = nameOnContacts === name;
    console.log(nameCheck);
    i++;
    console.log(i);
  };
 
};

lookUpProfile("Akira");

What the console output:

›
false
›
0
›
Akira
›
true
›
1
›
Harry
›
false
›
2
›
Sherlock
›
false
›
3
›
TypeError: contacts[i] is undefined (/index.js:28)
/index.html
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

while loops as long as the condition is true. With logical OR (||) only one of the conditions needs to be true in order for the loop to continue. You want the logical AND (&&)

const contacts = [
  {
    firstName: "Akira",
    lastName: "Laine",
    likes: ["Pizza", "Coding", "Brownie Points"],
  },
  {
    firstName: "Harry",
    lastName: "Potter",
    likes: ["Hogwarts", "Magic", "Hagrid"],
  },
  {
    firstName: "Sherlock",
    lastName: "Holmes",
    likes: ["Intriguing Cases", "Violin"],
  },
];

function lookUpProfile(name) {
  var nameCheck = false;
  console.log(nameCheck);
  
  var i= 0;
  console.log (i);

  while (nameCheck == false && i < contacts.length){
    var nameOnContacts = contacts[i].firstName;
    console.log(nameOnContacts);
    nameCheck = nameOnContacts === name;
    console.log(nameCheck);
    i++;
    console.log(i);
  };
 
};

lookUpProfile("Akira");

EDIT: If you are writing ES6 Code, these are the solutions I would have taken:

if you just want to find out if the name is already in the array, the Array.prototype.some function can be used, if you also want to know the index of the found element, you can use Array.prototype.findIndex:

const name = "Akira";
// function to check a single element
const firstNameMatches = (element) => element.firstName === name;
// is the name in the array at all?
const isInArray = contacts.some(firstNameMatches);
// to get the index of the found element or -1 if not found
const foundIdx = contacts.findIndex(firstNameMatches)
about 4 years ago · Juan Pablo Isaza Relatório

0

just adding a little bit of additional info. Douglas Crockford suggests in his book, “Javascript: The Good Parts”, that it’s always better (to avoid ambiguity) to use the identity operator. In otherwords, it's better to use "===" instead of "=="

https://medium.com/@ludico8/identity-vs-equality-battle-of-understanding-vs-758d396e922

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda