little help with javascript while loops
let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;
while (friends.length > counter){
if (typeof friends[counter] === typeof 1){
continue;
}
console.log(friends[counter])
counter++;
}
// idk why the loop won't do what i want
18 Replies
i want to print all the strings without the numbers and i know the continue would skip them but i get into a infinite loop
you never increment the counter if it's a number
when the loop hits a number, it stops incrementing the counter because the continue skips over
counter++
and keeps examining the same field in friends
over and overIs there a reason you're using a
while
loop here instead of a .forEach()
, for...of
, or plain ol' for
loop?Counter++
Simple challenge to use Javascript Properties
I've done it with for loop more than once but idk why it's like that with while loop
The break property works fine but the continue doesn't for some reason
Well, all you have to do is swap the
if
check and the console.log()
(and change the if
to check for strings). That way, if it's a string it's logged. Otherwise it just counter++
sis there a problem with the continue property in while loop ?
did it and the same thing
with the break it works with the continue it won't
No problem per sé but you're doing more work than needed IMO
i'll use codepin maybe it's problem with VSCODE
This works perfectly fine for me
All I did was change the
if
to look for strings and put the console.log()
inside the if
blockYes ! that did work
i guess i have to try multiple ideas with JS lol
While it's nice to know that you can do things multiple ways, most of the time the most efficient way is what you should learn and practice.
You (shouldn't) ever see something like this in production code. It'll more likely than not be either
.forEach()
or for...of
. Older devs will fall back to the for
loop, but it's more verbose and error prone than .forEach()
or for...of
yah i'm learning JS from the start and going into the available stuff one by one with ES6 and trying to get used to debug it
thank you for the help ! greatly appreciate it
If you haven't yet, check out https://javascript.info
It's full of, well JS info designed to teach bit by bit and I think it does a wonderful job at it
:0 more info for me !
that is so well designed and explained!
Isn't it!?!?!?