0

My code is not working (help)

var yourName = prompt("your name please"); var namesList = ["john", "bob", "lux"]; for ( i = 0; i < 3; i++){ if ( yourName === namesList[i] ){ document.write("your name on list") ; break; } else { document.write("not on list") ; break; } } when i enter john its true but bob and lux is false whats wrong ?

12th Nov 2016, 5:48 PM
moaaz.m.f
moaaz.m.f - avatar
6 Answers
+ 5
you have placed a 'break' command inside the 'else' condition. since 'else' is always entered if the 'if' does not enters, you simply break the loop and end the program before even examining the rest of the array. you only checked at the first index of the array and then broke the loop
12th Nov 2016, 6:03 PM
Burey
Burey - avatar
+ 5
there you go var yourName = prompt("your name please"); var namesList = ["john", "bob", "lux"]; var found = false; for ( i = 0; i < 3; i++){ if ( yourName === namesList[i] ){ document.write("your name on list") ; found = true; break; } } if(!found) document.write("not on list") ;
12th Nov 2016, 6:48 PM
Burey
Burey - avatar
+ 1
Break will always stop a function the moment it is encountered, preventing the remaining loops from completing.
20th Dec 2016, 10:44 PM
Robert Jones
Robert Jones - avatar
0
still not working
12th Nov 2016, 6:43 PM
moaaz.m.f
moaaz.m.f - avatar
0
I guess just use == instead of ===
14th Nov 2016, 1:19 AM
mahesh pullareddy
mahesh pullareddy - avatar
0
Object types are not equal
28th Jan 2017, 11:02 AM
Š•Š²Š³ŠµŠ½ŠøŠ¹
Š•Š²Š³ŠµŠ½ŠøŠ¹ - avatar