COMP519 Practical 5 JavaScript (1)

Similar documents
COMP284 Practical 6 JavaScript (1)

COMP519 Practical 15 PHP (1)

COMP284 Practical 3 Perl (3)

COMP519 Practical 16 PHP (2)

COMP284 Practical 1 Perl (1)

COMP519 Practical 14 Python (5)

CSC Web Programming. Introduction to JavaScript

Introduction to Lab Practicals (Lab Intro 3) Access Control, Synchronisation and Remote Access

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

COMS 469: Interactive Media II

Software and Programming 1

JavaScript: Introduction, Types

Working with JavaScript

c122mar413.notebook March 06, 2013

Variables and Typing

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

COMP 202 Java in one week

Introduction to Web Development

Department of Computer Science University of Pretoria. Introduction to Computer Science COS 151

Mobile App:IT. Methods & Classes

CS 11 java track: lecture 1

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

S8352: Java From the Very Beginning Part I - Exercises

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

1. Download the JDK 6, from

CSCU9B2 Practical 1: Introduction to HTML 5

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Full file at

COMP1007 Principles of Programming

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

Client Side JavaScript and AJAX

AP Computer Science Unit 1. Programs

Software and Programming 1

COMPSCI 120 Fall 2017 Review Questions for Midterm #2 Professor William T. Verts

Introduction to Java

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Chapter Two Bonus Lesson: JavaDoc

Java: Comment Text. Introduction. Concepts

PHP. Interactive Web Systems

Algorithms and Programming I. Lecture#12 Spring 2015

Program Fundamentals

3 The Building Blocks: Data Types, Literals, and Variables

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

CS 177 Recitation. Week 1 Intro to Java

CPS109 Lab 1. i. To become familiar with the Ryerson Computer Science laboratory environment.

Introduction to Programming Using Java (98-388)

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

Programming language components

Web Scraping with Python

CS50 Supersection (for those less comfortable)

1.00 Lecture 4. Promotion

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

First Java Program - Output to the Screen

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Task-Oriented Solutions to Over 175 Common Problems. Covers. Eclipse 3.0. Eclipse CookbookTM. Steve Holzner

Lecture 3: Web Servers / PHP and Apache. CS 383 Web Development II Monday, January 29, 2018

A340 Laboratory Session #5

Primitive Data, Variables, and Expressions; Simple Conditional Execution

1007 Imperative Programming Part II

1B1a Programming I Getting Started

PROGRAMMING FUNDAMENTALS

Beginning HTML. The Nuts and Bolts of building Web pages.

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

INTRODUCTION TO JAVASCRIPT

introjs.notebook March 02, 2014

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

AP Computer Science Unit 1. Writing Programs Using BlueJ

Simple Java Reference

13 th Windsor Regional Secondary School Computer Programming Competition

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Installing VS Code. Instructions for the Window OS.

Quiz 1 Review Session. November 17th, 2014

Getting started with Java

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

JavaScript CS 4640 Programming Languages for Web Applications

Introduction to Java Applications

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

Program Control Flow

Program Control Flow

Chapter 2 Working with Data Types and Operators

What is PHP? [1] Figure 1 [1]

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

Programming Language Basics

Program Design Phase. Algorithm Design - Mathematical. Algorithm Design - Sequence. Verify Algorithm Y = MX + B

Introduction to Computation and Problem Solving

Lecture 4: Introduction to Java and your Development Environment

Chapter 2: Programming Concepts

CIS 130 Exam #2 Review Suggestions

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Agenda. My Introduction. CIS 154 Javascript Programming

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Transcription:

COMP519 Practical 5 JavaScript (1) Introduction This worksheet contains exercises that are intended to familiarise you with JavaScript Programming. While you work through the tasks below compare your results with those of your fellow students and ask for help and comments if required. This document can be found at http://cgi.csc.liv.ac.uk/~ullrich/comp519/notes/practical05.pdf and you might proceed more quickly if you cut-and-paste code from the PDF file. Note that a cut-and-paste operation may introduce extra spaces into your code. It is important that those are removed and that your code exactly matches that shown in this worksheet. The exercises and instructions in this worksheet assume that you use the Department s Linux systems to experiment with JavaScript. If you want to use the Department s Windows systems instead, then you can do so. To keep things simple, we will just use a text editor, a terminal, and a web browser. You can use whatever text editor and web browser you are most familiar or comfortable with. If you do not manage to get through all the exercises during this practical session, please complete them in your own time before the next practical takes place. Exercises 1. Let us start by re-creating the Hello World JavaScript example that you have seen in the lectures. It is assumed that you have already created a sub-directory called public_html in your home directory and that the directory is both readable and executable by everyone. Make sure that this is so before you proceed. a. Open a text editor and enter the following HTML markup and JavaScript code: <!DOCTYPE html> <html> <head> <title>hello World</title> </head> <body> <script id="s1"> // Script with id s1 <p>our first JavaScript script</p> <script id="s2"> // Script with id s2 user = "<your name>"; document.writeln("<p><b>hello " + user + "<br>\nhello World!</b></p>") <script id="s3"> // Script with id s3 1

<p>this is the rest of the page</p> <noscript>javascript not supported or disabled</noscript> </body> </html> Replace <your name> with your own name. Note that there are three JavaScript scripts in this code. In order to be able to refer to each of these three scripts they have been given the ids s1, s2 and s3. We will use these ids in the instructions below. b. Save the code to a file named jsdemo05a.html in $HOME/public_html/. c. Open a terminal, go to the directory in which the file has been stored and make sure that the file is only readable by yourself and nobody else can read, write or execute the file: chmod u+r,og-rwx $HOME/public_html/jsDemo05A.html (Note: No space after the comma!) You will only have to do so once. File permissions should not change while you continue to edit the file. d. Now open a web browser and access the URL http://student.csc.liv.ac.uk/ <user>/jsdemo05a.html where <user> should be replaced by your username. Check that the page looks as expected and also that the HTML code producing the web page you are shown is exactly the HTML code you have seen in 1a above, including the JavaScript code. e. If already at this point or in one of the later exercises the web browser does not show the expected result, you will have to debug your code. For that you will need access to some diagnostic output for the JavaScript code that you have written. A lot of web browsers provide developer tools including a console on which errors are shown. For example, in Firefox the console can be found in the Tools menu. The shortcut CTRL+SHIFT+I in Firefox also opens the error console. Figure out how to access the console in your web browser and open it. If the web browser you use does not have a console (or you cannot figure out how to open it), switch to a better browser. f. To see how the console works let us introduce an error into our JavaScript code. At the end of the script with id s2 insert document.writeln("(1) The value of userage is: " + userage + "<br>") document.writeln("(2) This statement is executed<br>") into jsdemo05a.html. Save the file again and refresh the page in your web browser. Note that the web page appears unchanged. In particular, the statements introduced in 1f seem to produce no output. However, in the console you should now see an error message indicating that userage has not been defined/declared. g. We should correct the error by adding a declaration for userage. First, try the following: Add var userage = "27" document.writeln("(3) The value of userage is: " + userage + "<br>") 2

at the end of the script with id s2 in jsdemo05a.html (that is, after the document.writeln statement that already uses userage). Save the file again. Clear the output shown in the console, then refresh the page in your web browser. The console should no longer show an error message and the web page should include the lines: (1) The value of userage is: undefined (2) This statement is executed (3) The value of userage is: 27 This shows you that in JavaScript a declaration of a variable does not have to precede its use in order to prevent a reference error, however the initialisation of a variable only affects code that is executed later (even if the initialisation is done as part of a declaration). But this principle only applies to a particular JavaScript code fragment enclosed in the tags <script> and as we will see next. h. Move the declaration var userage = "27" from the script with id s2 to the script with id s3. Save the file again. Clear the output shown in the console, then refresh the page in your web browser. Is the code correct now or does it produce an error? What does that tell you about the scope of a variable declaration? i. Move the declaration var userage = "27" from the script with id s3 to the script with id s1. Save the file again. Clear the output shown in the console, then refresh the page in your web browser. Is the code correct now or does it produce an error? Is the output the same as in Exercise 1g? If not, why not? j. We need to consider one more possible way in which the scope of variable declarations might work. In a lot of programming languages, the scope of a variable is restricted to the block in which it is declared. For example, a variable declared in the then-branch of a conditional statement has the then-branch as its scope. On the else-branch of the same conditional statement (or anywhere else), the variable would be undeclared. Let us see whether this is the case for JavaScript. Add the following code before the noscript-element in jsdemo05a.html: <!-- Exercise 1j --> <script id="s4"> if (false) { var x = 519; else { document.writeln("the value of x is " + x + "<br>"); (Note the syntax used for the comment. The comment is not within the script but within the surrounding HTML markup. So, the syntax for HTML comments is used.) 3

Save the file. Clear the output shown in the console, then refresh the page in your web browser. What output or errors does the script produce now? k. In the script with id s4, replace the declaration var x = 519; by var y = 519; Save the file. Clear the output shown in the console, then refresh the page in your web browser. What output or errors does the script produce now? What do Exercises 1j and k tell you about the scope of variable declarations in JavaScript? What do Exercises 1j and k tell you about the way JavaScript code is executed? If there were any errors produced in the last two steps, try to fix them now. 2. Let us compare floating-point arithmetic in Java and JavaScript. a. To do so, first create the following Java program: import java.io.*; public class MathLibraryExample { public static void main(string[] args) { System.out.print("Input : "); int i = Integer.parseInt(System.console().readLine()); double d = Math.sqrt(i); double e = 4 / d; double f = Math.round(e); System.out.println("sqrt(" + i +") = " + d); System.out.println("4/" + d + " = " + e); System.out.println("round(" + e + ") = " + f); System.out.println(e + " > 0 : " + (e > 0)); System.out.println(e + " <= 0 : " + (e <= 0)); for (d = 0.4; d < 0.7; d = d + 0.1) { double r = i + d * Math.signum(i); System.out.println("round(" + r + ") = " + Math.round(r)); Save this as MathLibraryExample.java, compile the file using javac. Then, using java, execute MathLibraryExample for the inputs 4, -4, and 0. Copy the outputs of the Java program to a text file so that you can later compare them with the corresponding outputs of a JavaScript program. b. Open a text editor and enter the following HTML markup below and save it as file jsdemo05b.html in $HOME/public_html/. <!DOCTYPE html> <html> <head> <title>math Example</title> 4

</head> <body> <script> var i = Number(prompt("Input :")); /* Complete the following three lines of code with assignments that correspond to the computations performed in the Java program */ var d var e var f document.writeln("sqrt(" + i +") = " + d + "<br>") document.writeln("4/" + d + " = " + e + "<br>") document.writeln("round(" + e + ") = " + f + "<br>") document.writeln(e + " > 0 : " + (e > 0) + "<br>") document.writeln(e + " <= 0 : " + (e <= 0) + "<br>") for (d = 0.4; d < 0.7; d = d + 0.1) { var r = i + d * Math.sign(i) document.writeln("round(" + r + ") = " + Math.round(r) + "<br>") </body> c. As indicated by the comment, complete the code so that the same calculatons are performed to compute d, e, and f as in the Java program. d. In a web browser access the URL http://student.csc.liv.ac.uk/ <user>/jsdemo05b.html where <user> should be replaced by your departmental user name. e. A so-called prompt will appear that allows you to enter a number (or anything else). Enter the number 4 and either click the OK button in the prompt or press return. In the brower window you should now see the results of the various computations. Are all the results the same as for the Java program produced for input 4? f. To repeat the computation for a different input, you need to refresh the page. Then a new prompt will appear. Enter -4 now and press return. Compare the results produced by the JavaScript program with those of the Java Program for input -4. g. Finally, refresh the page again, enter 0, and press return. Compare the results produced by the JavaScript program with those of the Java Program for input 0. h. Make sure that you understand what is going on for each of the three inputs. 3. The precision of 64-bit floating-point numbers is necessarily limited. This problem is aggravated by the fact that the binary representation of these floating-points numbers allows to precisely represent a lot of binary fractions, e.g. 1/8 and 1/128, but not the decimal fractions that humans use, e.g. 1/10 and 1/100. The following example illustrates that. a. Create a file jsdemo05c.html in $HOME/public_html/ with the following content: <!DOCTYPE html> <html> <head> 5

<title>math Example 2</title> </head> <body> <script> var x = 0.3-0.2; var y = 0.2-0.1; document.writeln("x = " + x + "<br>"); document.writeln("y = " + y + "<br>"); document.writeln("(x == y) = " + (x == y) + "<br>"); document.writeln("(x == 0.1) = " + (x == 0.1) + "<br>"); document.writeln("(y == 0.1) = " + (y == 0.1) + "<br>"); </body> </html> b. Open the URL http://student.csc.liv.ac.uk/ <user>/jsdemo05c.html in a web browser, where <user> should be replaced by your departmental user name. c. Have a look at the output produced by the JavaScript program. Use an on-line decimal to floating-point converter such as http://www.binaryconvert.com/convert_double.html http://www.exploringbinary.com/floating-point-converter/ to understand what the floating-point numbers corresponding to 0.3, 0.2, 0.1 really are and what the results of 0.3 0.2 and 0.2 0.1 are. 6