a. How to master JavaScript


    Start using JavaScript

    How to start using JavaScript

    The browser can run in many different environments, but in this course we're going to focus on how JS is primarily used: in the browser. JS is an amazing language because we don't need to install anything to work with it--we just need an HTML document (a file that ends with .html) and we can start using it.

    To run JS we just need a set of script tags. So let's create a basic HTML document:

      <head> </head>

    Script tags

    Our script can be put in any part of document. Most of the time though it's at the end of the body, after all of the HTML. Scripts are executed right as the browser sees them, from top to bottom. Also having our JS code afterwards is essential because most of the time we want to change our HTML dynamically with JS.

    script tags have an opening and closing tag. Between them we put the JS code we want to run.

    Let's write our first program, which will tell our user 'hello world'. We can log some text to our console down here by saying console.log('hello world'). Note a couple of things there--the console.log is going to be useful throughout the course in displaying certain values or looking at certain parts of our program. And second, we are writing the text hello world between a set of quotes. All text in JavaScript has to be wrapped in quotes for it to be valid. Text in JavaScript like this is called a string.

      <head> </head>
          console.log("Hello world");

    So if we run this code by hitting the run code button or using the shortcut command or control S [run code], we see our text hello world in our console down here.

    Congratulations! You already know the core structure of any JS app, whether simple or complex.

    Most programs are not written in entirely within script tags, though. Only the most basic ones. Most of the time, our JS lives in a separate file.

    To create a JS file, we can name it whatever we like, but it has to end with the .js extension. If it's a project with just one .js file, it will likely be called index.js or app.js. We'll call it index.js, then put our previous program in it:

    // index.js
    console.log("Hello world");

    Then to still have our code run, we reference the js file using the src attribute on the script tags:

    <!-- index.html -->
    <script src="index.js"></script>

    When we save, it still runs as before.

    So we covered two types of writing JS code: inline code between script tags and using external scripts. Throughout this course, we'll use external scripts to write our programs

    My challenge to you to finish up this lesson is to write an external script called app.js instead of index.js. And then get app.js to console.log your own custom text to the user.