Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Questions on javascript code

Hi I trying to learn javascript so I thought I'd start by reading the book eloquent javascript...

Inside the book there a few exercises along the way.

one of the exercises is to achieve this pattern below with code:

The answer in the book is this code:

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

I understand it all except 'line +="#"'. I thought # would be consider a string and therefore this method would not work. Could someone explain how this works and are there other ways of writing this part. Any help is much appreciated

1 Answer

What this code is doing is adding another hashtag to the end of line variable each time the loop is run. The results of the code in the console is:

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

yeah but why are you allowed to do

line+= "#"

is the # not consider a string. In the same book it says you can only use + to concatenate strings. I understand what is doing I just would like to know why or maybe I'm just getting it confused.

Oh, this += is a shorthand operator that is telling the browser that you want to reassign the value of the line string to be the previous value with a "#" concatenated at the end.

line += "#";

// This is the short form of...

line = line + "#";

Only If you have time please take a look at this code also:

for (var n = 1; n <= 100; n++) {
  var output = "";
  if (n % 3 == 0)
    output += "Fizz";
  if (n % 5 == 0)
    output += "Buzz";
  console.log(output || n); //dont understand
}

I understand everything its doing and purpose except the console.log part I'm not sure what it will print and why it prints that part.

the || operator means "or" It can be used in a few ways, such as part of a conditional "if" statement, or to define a value.

What is happen with console.log(output || n) is you are telling the browser to log the output variable if it has a truthy value, but if it does not, log the value for the n variable instead. So basically, log output or n.

I hope that makes sense!