When we need to perform similar actions for certain number of times, that is when we get to “Looping”.
For example, when we need to output goods from a list one after another. Or just run the same code for each number from 1 to 10.
Loops are a way to repeat the same part of code multiple times.
In Javascript, there are while loop, for loop and do-while loop. In this post, the while and for loop will be compared.
The syntax for while loop is :
while (condition) {
// code
// so-called "loop body"
}
the syntax for for loop is :
for (begin; condition; step) {
// ... loop body ...
}
So what is the deal with for loop?
For Loop allows you to run through the loop when you are certain as to how many times you would like it to run through the data structure such as for (var i; i < 9; i++); this will continuously increment i until the condition returns false (i is no longer less than 9). Any number can replace the 9 even a different type of variable. But the loop will terminate once the condition is no longer met.
How about a while loop?
A while loop can be used when you need your loop to run an unknown number of times until a specific condition is met.
Let’s use a contrived example. If you are making a tax calculator that allows a human resource manager to see how much tax that each employee out of ALL employees has to pay. The person who uses the calculator will have to input the number of employee that the loop will iterate through, like so :
let totalEmployee = prompt("Please input the total employee");
let i = 0; // the iterator
let tax = {}; // key-value pair for calculated tax for each employee
while(i <= totalEmployee){ ... assign the value of the tax for each employee here ... }
// execution stops after counting the tax of the last employee
So how are they different from each other?
The key differences between the two loops lie in the intention “why do we need looping for?” and “do we know the condition at which the loop will stop?”
Use for loop if you know the condition or when to end or break the iteration.
Use while loop if you were to use an existing variable (purposefully using VAR keyword that is not block-scoped) in your program; or when your condition uses a new value that is obtained through the interface (like prompt / asking a user to input a number in the calculator example above).
Special to JS though, the iterating variable i for instance can be bound within the block of the for loop if it is defined by the let keyword which makes the for loop safer for some inexperienced JS programmers.
Long story short : The for loop is mostly preferred for the simple iteration jobs while the while loop is more applicable when you need to implement something at a frequency of iteration that is not yet certain or is a dynamic value that will depend on the interaction with other aspects/variables in your program.
Why let for the for-loop?
It has something to do with block-scoping for variables.
Say you have a program with one for-loop in it.
If your for loop has i instance, when you also have i in the outer scope like so :
// outermost scope of the program
var i = "Hello World";
console.log("what is i : i is", i); // prints "What is i : i is Hello World"
// but then you have for-loop below
for (var i = 0; i < 9; i++) {
// block-scope of for loop here
}
// let's use the same variable i below :
console.log("what is i : i is", i) // what will be printed to the console? what will be the value of i?
In the example, we are touching the issue of “block scoping”. Read more about it here.
After the closing curly brace, the execution goes back to the outer scope. If you need the same i instance, that was assigned to be “Hello World” before the for-loop begins, the i instance will no longer have the same value. The i in the for loop will override / reassign the value of i, resulting in the console.log to display :
What is i : i is 9 // not "Hello World"
This problem is caused by the fact that var is not block-scoped, so the value spills over all over places, in and outside for-loop. This can be mitigated with the use of LET in replacement of VAR. It is all due to LET having the power to turn variables only applicable within its block.
viagra 100mg price buy viagra cheap viagra
cost of viagra buy viagra generic viagra pills
generic cialis available generic cialis 30 day cialis trial offer
where to buy viagra online viagra for sale viagra without a doctor prescription
help with ed ed cures that work best male enhancement
generic viagra online buy viagra online price of viagra
generic viagra without a doctor prescription generic viagra viagra prescription online
best place to buy generic viagra online cheap ed pills can you buy viagra over the counter
generic viagra online for sale cheap ed pills viagra online canada
generic viagra cost buy viagra from canada no prescription viagra
the best ed drug ED Pills Without Doctor Prescription ed medications list
best ed pill Cheap Erection Pills buy prescription drugs without doctor
best pills for ed generic cialis ed clinics
buy online pharmacy ED Pills amoxicillin without a doctor’s prescription
cialis for peyronie buy tadalafil cialis professional
cialis vs levitra buy cialis cialis coupons 2019
best ed pills at gnc generic ed pills errectile dysfunction
solutions for ed
ed treatment review ed medications online ed doctor
ed medications online
homepage canadian medications doctors for erectile dysfunction
over the counter ed treatment
https://amoxicillingeneric500.com/ amoxicillin 500 mg tablet
https://zithromaxgeneric500.com/ zithromax 500 mg
https://zantacgeneric150.com/ order zantac
https://prednisonegeneric20.com/ prednisone without prescription.net
drugs from india buy generic drugs online
buy generic drugs online pharmacy
buy tadalafil online generic tadalafil
india pharmacy drugs from india
medicines for ed https://sildenafilxxl.com/ buy viagra online canada
pumps for ed cheap Prednisone prescription drugs online without doctor
ed help canada online pharmacy erectial dysfunction
cialis lowest price 20mg cialis for sale how does cialis work
viagra cialis generic viagra where to get viagra
cheap medications online buy Nolvadex buy cheap prescription drugs online
cialis vs levitra generic cialis cialis free trial
warnings for cialis generic cialis where to get cialis sample
what causes ed: canadian medications ed treatments that really work
errection problem cure: natural drugs for ed sexual dysfunction in men
best erectile dysfunction pills: dog antibiotics without vet prescription prescription drugs canada buy online
best online pharmacy
aurogra 100 for sale
drug store online: best ed pill cheap ed pills
price of levaquin
live sex chat online
do i have ed: how to cure ed what causes ed
cialis on sale
ed pumps: how to overcome ed naturally best ed pills non prescription
camgirl
state farm life insurance
retino 0.025 cream
safeco car insurance
fildena 100 mg price
edison insurance company
generic zithromax azithromycin buy zithromax 1000 mg online zithromax over the counter canada
buy cheap sildenafil online
ed and diabetes approved canadian pharmacies online ed for men
is there a generic viagra how to get viagra without a doctor mexican viagra
universal home insurance
canadian viagra generic viagra online for sale cheap viagra
zithromax 500mg price in india zithromax antibiotic without prescription zithromax for sale us
personal loans guaranteed approval
cash lenders
can you buy zithromax over the counter zithromax online usa no prescription buy generic zithromax online
daily use cialis cost otc cialis interactions for cialis
hoodia prices
omnicef brand name
buy viagra canada fast shipping
online homeowners insurance quotes
cost of viagra in usa
where can i buy viagra https://genericvgr100.online generic viagra walmart
payday loans in cleveland ohio
debt consolidation loan low interest
viagra discount https://genericvgr100.com when will viagra be generic
cialis work for women accuttincant cialis online Mentitunty Generic Real Isotretinoin Best Website C.O.D. Cheapeast Shop
viagra discount https://genericvgr100.com viagra over the counter walmart
canadian pharmacy viagra prices
universal property insurance
2.5 mg cialis daily
viagra 100mg cost in usa
need a loan immediately
house insurance company
where to get cialis in singapore
house insurance comparison sites
buy lasixonline
Flagyl antibiotics Amoxil antibiotics prescription drugs online without doctor
treating ed best erectile dysfunction pill erectile dysfunction pills
100mg viagra
best ed medications Zovirax buy Zovirax
pay day
amox k 875 125 buy Flagyl cheap pills online
affordable home insurance
instant payday
ed products canada prescription pharmacy certified canadian online pharmacies
viagra 37500
online viagra can you buy viagra over the counter how much will generic viagra cost
social loan
home insurance
generic tadalafil cost
tadalafil without a doctor’s prescription ed pills that work 100mg viagra without a doctor prescription
nizoral where to buy
ed meds pills drugs ed medications online drugs causing ed
plaquenil for lyme
natural ed drugs canada drugs canadian online pharmacies
quick money
canadian pharmacy viagra cheap viagra online canadian pharmacy viagra 100mg
buy prescription drugs from canada canada online pharmacy fda approved canadian online pharmacies
cialis and interaction with ibutinib cialis 20 mg best price cialis prices
stromectol tab price
tadalafil cost india
loan assumption
reputable debt consolidation
how much will generic viagra cost https://cheapvgr100.online/ krjudplb
get cash now
sildenafil 75 mg
myambutol 400 mg tab
best place to buy viagra online https://cheapvgr100.com/ spitlikk
hjnmcdlt viagra viagra cost
cash today
viagra pills 150 mg
where can i buy oral ivermectin
loans in tucson
get loan
where can you buy zithromax drug bactrim antibiotic smz tmp ds
viagra cost prescription
zyrtec 10.00 coupon periactin canada otc allegra over the counter coupon
loans online guaranteed
valacyclovir famvir online pharmacy acyclovir tablets
yasmin pill cost uk alesse for acne alesse for acne
125 mcg digoxin
buy ceftin 250 mg without a prescription
cialis canada for sale
bactrim medicine bactrim ds medication doxycycline hydrochloride 100mg
sildenafil nz buy
order clomid yasmin uk buy serophene tablet
top 10 payday loans
zyrtec australia zyrtec 90 benadryl 5 mg tablet
acyclovir online pharmacy zovirax cream price acyclovir buy online
direct loans student
how much is generic valtrex zovirax online uk famvir 500 mg price
purchase zoloft online
where can i get viagra prescription
pil https://vgr24w.com/ sep
ust jnf
order levitra online in usa
gzi https://vgr24w.com/ qal
ncc vah
medicine flonase
bad credit short term loans
tadalafil generic south africa
Woah! I’m really enjoying the template/theme of this
blog. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between user friendliness and visual
appeal. I must say you’ve done a excellent job with this.
Also, the blog loads very quick for me on Internet explorer.
Excellent Blog!
loans for people with no credit
cheap cialis canada pharmacy
online pharmacy australia viagra
Pingback: cheap cialis generic
does viagra or cialis help with pe http://cialisirt.com/ herbal replacement for viagra/cialis/levitra… laeefnfw
I do accept as true with all of the ideas you have presented on your post. They’re really convincing and will certainly work. Still, the posts are too short for newbies. May just you please prolong them a little from next time? Thank you for the post.
where to buy viagra online http://viagrastm.online/ viagra from india
viagra cost per pill http://viagrastm.online/ canadian pharmacy viagra fiirrzhy
Pingback: how hard can i get with cialis vs viagra vs levitra
same day payday loan
canadian pharmacy viagra http://viagrastm.online/ how to get viagra without a doctor izwfsabf
orlistat alli
canada cialis http://cialisirt.com/ generic cialis bitcoin
cheap generic viagra http://viagrastm.online/ viagra professional wulllrug
It’s truly very complex in this busy life to listen news on TV, thus I just use internet for that
purpose, and obtain the most up-to-date information.
easy money payday loans
best female viagra tablets in india
order cialis online pharmacy
viagra http://viagrastm.com/ is there a generic for viagra imgjazby
I blog frequently and I genuinely appreciate your information. The article has truly peaked my interest.
I will take a note of your website and keep checking for new information about
once a week. I subscribed to your Feed as well.
prescription for viagra
Pingback: marley drug viagra
Hey would you mind letting me know which web host you’re using?
I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most.
Can you recommend a good internet hosting provider at a fair price?
Kudos, I appreciate it!
$200 cialis coupon http://cialisirt.com/ cialis without doctor prescription
low rate personal loans
generic cialis online fast shipping
ceftin 250 mg price in india
Pingback: viagra trial sample
viagra for women over the counter
I seriously love your site.. Excellent colors
& theme. Did you build this amazing site yourself?
Please reply back as I’m looking to create my own personal site
and would love to find out where you got this from or exactly what the theme is named.
Thank you!
malegra
Hey there just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Chrome.
I’m not sure if this is a format issue or something to do with
internet browser compatibility but I thought I’d post to let you know.
The design and style look great though! Hope you get the issue fixed soon. Cheers
can i buy viagra without a prescription
Pingback: cialis pro 40
bystolic buy
ed medicine https://canadianpharmacyvikky.com ed medications online
bad credit payday advance
cat antibiotics without pet prescription https://canadianpharmacyvikky.com pain meds online without doctor prescription
I love what you guys are usually up too. Such clever work and coverage!
Keep up the excellent works guys I’ve incorporated you guys to my own blogroll.
no fax payday loans
tadalafil without a doctor’s prescription https://canadianpharmacyvikky.com ed pumps
viagra prescription discount
Hi would you mind sharing which blog platform you’re working with?
I’m planning to start my own blog in the near future but I’m having
a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I’m looking for something
unique. P.S My apologies for being off-topic but I had to ask!
viagra for sale in usa
cash lenders
generic for zantac generic zantac recall
uk viagra prices
I’ve been surfing online more than 2 hours today, yet I never found any interesting article like
yours. It is pretty worth enough for me. Personally, if all site
owners and bloggers made good content as you did, the net will be much more useful than ever before.
compare cialis prices uk
loans for poor credit
loan personal
compare prednisone prices prednisone 2.5 mg tab
same day payday loan
valtrex without prescription valtrex best prices
valtrex over counter buy valtrex without get a prescription online
I will immediately take hold of your rss feed as I can not in finding your e-mail subscription hyperlink
or e-newsletter service. Do you’ve any? Kindly let me realize in order that
I may subscribe. Thanks.
zithromax 1000 mg online zithromax over the counter uk
generic cialis tablets
how much is valtrex in canada cheapest on line valtrex without a prescription
online viagra in us
amoxicillin tablet 500mg price for amoxicillin 875 mg
best price for viagra in us
payday loans columbus ohio
rx pharmacy online erectile dysfunction canadian pharmacy cialis
buy 40 mg tadalafil online
Hi there! I could have sworn I’ve visited this web site before but after looking at many of the posts I realized it’s new to me.
Anyhow, I’m certainly happy I came across it and I’ll be book-marking it and checking
back frequently!
ventolin without a prescription can i buy ventolin over the counter nz
rx express pharmacy best erectile dysfunction pills thrifty drug store
hassle free payday loans
best drugstore liquid eyeliner canada drug pharmacy indian pharmacy online
These are genuinely great ideas in about blogging. You have touched some good factors here.
Any way keep up wrinting.
short term loan rates
best online pharmacy pharmacy discount card express scripts pharmacy
viagra generic discount
rx pharmacy http://pharmacy-onlineasxs.com/ best drugstore liquid eyeliner
best drugstore eye cream rx pharmacy coupons pharma
valtrex online prescription
Pingback: otc viagra us
Thank you for the good writeup. It in fact was a amusement
account it. Look advanced to more added agreeable
from you! However, how can we communicate?
cialis over the counter canada
fast loans no credit
Pingback: drug interaction finesteride and cialis
claritin 25 mg
rx pharmacy pharmacy today discount rx
It is appropriate time to make some plans for the future and it’s
time to be happy. I have read this publish and if
I may I desire to counsel you some attention-grabbing things or tips.
Perhaps you could write next articles referring to
this article. I desire to read even more issues approximately it!
what type of medicine is prescribed for allergies https://canadarx24.com/ mexican pharmacy without prescription
sildenafil discount
24 hr pharmacy best online pharmacy my canadian pharmacy
Pingback: generic viagra without
cashnowoffer tracking
ed meds online without doctor prescription https://canadarx24.com/ comparison of ed drugs
I’ve been surfing on-line greater than 3 hours as of late, but I by no means discovered any interesting article like yours.
It is lovely price enough for me. In my opinion, if all webmasters and bloggers
made excellent content material as you probably did, the net shall be a
lot more useful than ever before.
buy ed drugs online https://canadarx24.com/ prescription drugs without prior prescription
cheapest place to buy viagra
topamax buy online
Hi everybody, here every one is sharing these kinds of know-how, therefore it’s fastidious to read this webpage, and I used
to go to see this weblog everyday.
viagra canada price
ed medication online https://canadarx24.com/ ed remedies that really work
get payday loan
buy viagra online mexico
medication for ed https://canadarx24.com/ ed treatment
viagra 25mg price
bad credit installment loans guaranteed
loans home
best place to buy viagra online uxoaxlwg sildenafil how to get viagra
levitra online uk
over the counter synthroid
generic cialis no doctor’s prescription cialis qlxjplno cialis money order
how much viagra should i take the first time? https://edcheapgeneric.com/ lliemvgf viagra professional
drug medication ncxrfddd cheap levitra how to overcome ed
prednisone online paypal
muse ed drug nnicvqgw order levitra help with ed
viagra 200mg pills
prednisolone 5mg without prescription
cialis maximum dosage buy cheap cialis qldhzubp cialis generic availability
cialis for peyronie cheap cialis cmzuujgv cialis erections
amazon viagra kaufen
cheapest cialis us
daily dose cialis cost Chugh Anync
best liquid cialis rgmusyix http://edcheapgeneric.online/ taking l-citrulline and cialis together
lending com
loans in raleigh nc
natural cures for ed ebiymjlv levitra generic compare ed drugs
where to buy sildenafil in south africa
30 mg tadalafil
can you buy viagra over the counter in colombia Chugh Anync
sildenafil without prescription from canada
how long does cialis last 20 mg
cialis price usa
mexican pharmacy real pfizer viagra Chugh Anync
xjhv viagra cheap http://dietkannur.org aorl ofdt
aykd over the counter viagra http://dietkannur.org vtbf rdwm
Pingback: buy cialis 36 hour
cialis discount card cialis online rqlpugrd walgreens price for cialis 20mg
price of cialis
affordable loan
high blood pressure and cialis cialis coupons 2019 ytmhhyih prices of cialis
coupon for cialis by manufacturer
best generic viagra in india
prednisolone 5mg tablet coupon
which is better – cialis or viagra generic cialis without prescription wiztljla cialis erection penis
retin a australia
quickloan
e payday loan
viagra over the counter which countries
viagra effectiveness
can you buy viagra from chemists Chugh Anync
azithromycin 500mg price in india
Pingback: cialis without prescriptions canada
printable viagra coupon
viagra tablets for sale
viagra price per pill cvs Chugh Anync