-1

Developing a program which allows people to enter the office based on there names, this is just a test program to practice and develop my skills in javascript... why does the "try again" statement get executed when there is a successful match between the users input and the my array?

    // program to allow people to enter the office
console.log("Welcome to Company X, Please follow the")

let Employees = ["Harry","Dom","j"]
let visitors = prompt("Hi, Enter your name")
let attempts = 0
let alert = 2

for(let i = 0; i<Employees.length;i++) {
   while(visitors!=Employees[i] && attempts<alert) {
   attempts = attempts + 1 
   visitors = prompt("try again")
  }  
   if(visitors===Employees[i]) {
   console.log("Please move forward")
   } 
  } 
   
if (attempts>=alert) {
  console.log("Security ON-ROUTE!")
} 
user13784117
  • 1,124
  • 4
  • 4

1 Answers1

1

let's think about what happens here.

first, you have "Harry" at Employees[0] and let's say I entered "Harry" as "visitors"

so the while loop have false condition and it will run console.log("Please move forward")

but it will not Stop, now the Employees[1] will be "Dom" so the While loop condition will be true and will ask you again for name, etc...

so one of the solutions is to add:

 if(visitors===Employees[i]) {
       console.log("Please move forward")
       i = Employees.length ;
       } 

but it will work only if you follow the order of the Employees Array.

DanTe
  • 115
  • 6
  • Hey Thanks .. I found the issue in hindsight use a break command in the if and while if(visitors===Employees[i]) { console.log("Please move forward") break } } if (attempts>=alert) { console.log("Security ON-ROUTE!") } – code_novice_1234 Jun 21 '20 at 15:03