Exercise 10.1

This is Exercise 10.1, lecture on Javascript basics, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.

Go back to exercise list.

Purpose

The purpose of the exercise is to try javascript in several ways: to run a JS code in the console, to include inline <script> block, and to include an external .js file.

Instructions

Step 1

Try JS in the console:

  1. Open Developer tool console in your browser (Ctrl+Shift+J in Chrome)
  2. Type the following command in the console: console.log("Hello, Javascript");
  3. You should see the text appearing in the console.
  4. Now try to set value for two variables a=2 and b=3, and then print out a+b in the console.

Step 2

Now let’s try to execute inline Javascript in HTML. Create a new HTML document, and create the following block in the head section:

        <script>
            a = 2;
            b = 3;
            console.log("The sum of a + b is", a + b)
        </script>
      

Open the file in the browser and look into the console. Do you see the output there? Now put another <script> block inside the body part of the document:

        <script>
            b = 12;
            console.log("Now (in the body) the sum of a + b is", a + b)
        </script>
      

What output do you see now in the console, if you refresh the page in the browser?

Step 3

Now let’s try to include an external JS file. Create a file hello.js, save it in the same folder where you have the HTML file. Place the following code in the hello.js file:

        a = 4;
        console.log("a times b is", a * b);
      

In the head section include the hello.js file you just created. You do that by inserting the following line of code after the existing inline <script> block:

<script src="hello.js"></script>

What happens if you move the import of the hello.js file before the inline-script block (the one you created in step 2)? Try that! Hint: you will see what happens when you try to use an unknown variable in Javascript.

Solution

You can find a solution for steps 2 and 3 here.