What's JavaScript Thinking Here?


#1

So I’m doing a classic beginner’s exercise, building a checkerboard pattern out of spaces and octothorpes (better know as “hashes,” “the pound sign,” and of course “the number sign”), like so:*

codecademy-forum-txt-ed-wtf

So that’s the goal. To make it clearer, I’m using “[]” instead of “#” – so the end result would look like this:

[]#[]#[]#[]#
#[]#[]#[]#[]
[]#[]#[]#[]#
#[]#[]#[]#[]
[]#[]#[]#[]#
#[]#[]#[]#[]
[]#[]#[]#[]#
#[]#[]#[]#[]

And here’s the code which I came up with that works:

for (var i = 0; i < 8; i++) {
	for (var j = i; j < 8 + i; j++) {
		if (j % 2 == 0) {
			document.write("[]");
		} else {
			document.write("#");
		}
	}
	document.write("<br>");
}

But I don’t understand JavaScript’s reasoning, though:

  1. Why do I need “j < 8 + 1” and not simply “j < 8” in order for the code to work?*

  2. Why do I need to use “[]” instead of " " – with a space – in order for the code to work?**

  3. Why can’t I use “j + 0” or “j = j” for the final expression – that is, instead of the usual “j++” – if with each pass j just gets set back to the value of i that this sub-loop started out with anyway?

  4. And why would “j + 0” or “j = j” for the final expression set off an infinite loop, evidently, freezing the browser tab?

I’ve actually solved this exercise before a year ago (trying to pick up coding again) but can’t for the life of me recall exactly what I’d done and this is the best I can come up with so far…thanks for any insight!

  • Using screenshots because the stupid forum text editor cuts things off as if I’m wasting bandwidth with whitespace!!!

** Else the output looks like this:

[]#[]#[]#[]#
#[]#[]#[]#
[]#[]#[]#
#[]#[]#
[]#[]#
#[]#
[]#

*** Else the output looks like this:

[stupid forum policy only allows a new user like me to upload one image per post so look below for the screenshot]


#2

you could, but then the initialization should be var j = 0.

the construction you currently have is an interesting one, it works but for the first row (first iteration of outer loop), the inner loop will loop through 0 till 8, while for the second outer loop the inner loop will loop through 1 till 9, then the next one 2 till 10, its not something i think i would do

better question: why use document.write? There are better alternatives. And if you use something better to wrap your rows (like a block <div></div>), you might be able to use spaces. Break is a dirty hack, preferable avoided.

because then the sub loop will never finish, you have an infinity loop.

do you understand how the nested loop works? here is an example:

for(var i = 0; i < 8; i++){
  for (var j = 0; j < 8; j++){
    console.log("j: " + j)
    console.log("i: " + i)
  }
}

the inner loop makes 8 iterations before the outer loop makes an iteration. Maybe this tool can help even better:

http://www.pythontutor.com/javascript.html#mode=edit

check out this topic:

How do I format code in my posts?

it teaches format, so your spaces stay preserved when posting code/output! very handy

If you ever make an application similar to this forum, you will understand why preserving spaces becomes a problem. You see this “problem” with most web forums.


#3

codecademy-forum-txt-ed-wtf2


#4

Haha, well of course but what I’d meant was “why doesn’t ‘var j = i; j <8; j++’ work?” Why does “j = i” and “j < 8 + i” have to go together??

But I’ve actually been able to understand this now: because I’ve pegged the value of j to i, I need a j to not simply be less than 8 but less than eight plus whatever i is because otherwise, the number of loops in this sub-loop go down as the value of i increases – so the value of i needs to be added “back in,” as it were, in order for this sub-loop to run eight times (instead of eight minus the current value of i).

I don’t want to create a whole webpage – even if it’s just the barest of HTML scaffolding involved…I like to just input my (attempt at) code into an online JS editor and see what blows up! :wink:

But what are these “better alternatives” you mention? Someone else – a “Roy” I think (IIRC), an old forum “mainstay” – had mentioned the same thing but even googling didn’t help me understand what the problem was. I mean, I learned that it wasn’t good to use for various reasons but none of them seem to apply to my use-case (though I must say I didn’t really understand those reasons anyway).

Yeah, no, I understand how to use the Discourse forum system – but the code wasn’t being displayed properly 'cause Discourse (or Codecademy’s implementation of it) kept wiping out my spaces (my whitespaces, which are integral parts of the output)!


#5

exactly, very good :slight_smile:

getElemenById to get a html element, and then innerHTML to insert inside this element, which is sufficient if you need simple DOM manipulation. (given DOM manipulation is expensive)

ideally, adding to DOM should be done in a single go, so if we need add multiple element we should first create the element in JS (using createElement) and append children (using appendChild) to this element, then insert in a single go into the webpage


#6

Thanks for helping me think this through!

I’m just playing around with code exercises, not constructing a “real-use” program…surely there’s no harm in using document.write() right now, right? I mean, I’m sure for real programs of course the output needs to be done in a better way somehow but right now I’m using document.write() and even alert() just to quickly see if my code (more to the point, my coding concepts, my code design) works…that’s why I still don’t understand what the “problem” is.

BTW, I think I’d read somewhere that even getElementByID and/or innerHTML are problematic for some reason or other…you know what, I’m going to read up even more on this and if I still don’t understand, I’m going to start a new topic (see ya there!)…I get the sense that there are performance issues involved, maybe even security issues, too, but I don’t really know and I definitely don’t know what’s wrong with it for quickly coding in an online editor.

Thanks again, though!


#7

i am sure they are, but so is document.write()

one of the drawbacks, for both document.write and innerHTML is this:

document.write("<script>alert('work')</script>");

i could just insert JS code. This becomes problematic when like this forum, users can type text. Then you need to sanitize the input.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.