jeudi 30 juin 2016

Can someone explain why this this for loop prints out this specific pattern?

I thought I had a good understanding of for loops, but now that I have started to try looping patterns with for loops, things have gotten a lot more confusing. For example, I know that the following code will print out:

for (var line = “#”; line.length < 8; line += “#”) console.log(line);

Output will be:

#
##
###
####
#####
######
#######

This is what I understand so far about this loop:

  1. Firstly, the loop is initialized by creating a variable “line” to store the value “#” which is only one character.
  2. Next, “line.length<8” checks that the length of the string stored in the variable “line” is less than 8 characters long.
  3. The third part “line += “#”” updates the value stored in the line variable by adding “#” for each iteration that line.length<8 is true.
  4. The length of the string (and therefore line.length) is being updated for each iteration of the loop because a “#” value is being added each time.

Can someone explain to me why # is being added once, then twice, then three times etc. From the (incorrect) understanding that I have, I keep thinking that it’ll look like:

#1
#2
#3

etc.

Aucun commentaire:

Enregistrer un commentaire