Running JS in the browser
- Create a folder called sandbox.
- In the sandbox folder create an html file called week1.html with the html for a basic page. (Hint: In VS Code type ! in your blank .html file...then press the tab key. You are welcome...;)
- Create a file called main1.js
-
Add a
scriptelement to your week1.html file. The script element is how we let the browser know that there is some Javascript code that it needs to fetch and execute.There are a few special elements in HTML. They are special because the contents of those elements are not treated as HTML, but something different.
<script>and<style>are the most common of these special tags. In the case of<style>the contents are treated as CSS (which we won't talk about much in this course). For<script>the contents are treated as Javascript.The
<script>can be used in two ways: we can add the code we want executed inside of the element, ie:<script> let myVar = 3; </script>...or we can put our Javascript code inside of a separate file and link it in:
<script src="main1.js"></script>This second method is considered best practice and is how we will run our Javascript in this course. The other method is often used for quick proof-of-concept hacking, but the code will usually get moved into a JS file if the code is going to be kept.
-
Add the following code to your main1.js file:
const PI = 3.14; const radius = 3; let area = 0; area = radius * radius * pi; radius = 4; area = radius * radius * pi; - Using the Liveserver extension open the week1.html file in a browser.
- There is nothing on the screen! This is normal...in our HTML we didn't ask for anything to be on the screen. Open up the developer tools...check the console.
- Fix the errors.
- Add a breakpoint and step through.
- Add some
console.logstatements - Refactor our area calculation to a function.
- Step into the function