JavaScript JavaScript Basics Introducing JavaScript The Console Challenge Answer

Kyle Masuga
Kyle Masuga
4,432 Points

Checking for "bugs" and thought I found one in index.html...

Can you explain why the

 is inside the closing tag for the 
```<div>```
 and not just before the closing tag for the 
```<body>```
?

I ask because I thought in one of the previous videos I understood that the 
```<script></script>```
 should be or can also be placed just before the closing 
```<body>```
 tag...
Shawn Flanigan
Shawn Flanigan
Pro Student 15,800 Points

Kyle: I reformatted your question to make it more legible. Whenever you want to reference an html tag, you'll need to go to a new line and wrap the code in 3 backticks (next to the 1 on your keyboard).

1 Answer

Shawn Flanigan
PRO
Shawn Flanigan
Pro Student 15,800 Points

Hi Kyle: Good question. You can place JavaScript anywhere throughout your document and it will run as the browser encounters it. In general, you're right...most people consider it best practice to try to put script tags as low on the page as possible, allowing all of the page content to load before running any JavaScript. Usually the content of the page will all need to be in place before you can attach event listeners or alter elements on the page.

The example in the video is a bit of a special case...it's simplified code and this isn't a way that you'd normally see JavaScript utilized. Here, they want the browser to run the JavaScript and insert content directly into the HTML before it is rendered.

This is probably a bad example, but imagine buying a dresser from IKEA and putting it together. Placing JavaScript at the end of your document would be similar to the following steps:

  • Assemble the outer shell of the dresser.
  • Assemble the drawers.
  • Install the drawers.
  • Open the top drawer and insert socks and underwear.
  • Open the middle drawer and insert shirts.
  • Open the bottom drawer and insert pants.

Scattering the JavaScript throughout the document would be similar to:

  • Assemble the outer shell of the dresser.
  • Assemble the top drawer.
  • Insert socks and underwear.
  • Install the drawer.
  • Assemble the middle drawer.
  • Insert shirts.
  • Install the drawer.
  • Assemble the bottom drawer.
  • Insert pants.
  • Install the drawer.

This probably doesn't make a lot of sense right now, but keep at it and it will all click before long.

Kyle Masuga
Kyle Masuga
4,432 Points

Makes sense. I appreciate your explanation and figured this was a 'special' example, just wasn't fully certain and thought maybe I had missed something. Thanks again for explaining.