COMP519 Web Programming
Lecture 10: JavaScript (Part 1)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 JavaScript
Motivation
Overview
Example
Scripts
Type Systems and Type Checking
2 Further Reading
COMP519 Web Programming Lecture 10 Slide L10 1
JavaScript Motivation
JavaScript: Motivation
HTML/CSS is sufficient for HTML documents aimed at
disseminating information that does not change too frequently
HTML documents that remain the same each time they are accessed
are called static web pages
; HTML/CSS is sufficient for static web pages
In order to develop interactive/reactive web pages we must integrate
programming in some form or another
One form is client-side programming/scripting:
Code is written in a separate programming/scripting language
Code is embedded in the HTML markup of a web page or
linked to from the page and accessible by the web browser
Code is executed by the web browers (or external run-time environment)
on the user’s device
COMP519 Web Programming Lecture 10 Slide L10 2
JavaScript Motivation
Scripting languages
Script
A user-readable and user-modifiable program that performs simple
operations and controls the operation of other programs
Scripting language
A programming language for writing scripts
COMP519 Web Programming Lecture 10 Slide L10 3
JavaScript Motivation
Scripting languages: Properties
Program code is present at run time and starting point of execution
compilation by programmer/user is not needed
compilation to bytecode or other low-level representations
may be performed ‘behind the scenes’ as an optimisation
Presence of a suitable runtime environment is required for the execution
of scripts
includes an interpreter, or just-in-time compiler, or bytecode compiler plus
virtual machine
typically also includes a large collection of libraries
Executation of scripts is typically slower then the execution of code that
has been fully pre-compiled to machine code
COMP519 Web Programming Lecture 10 Slide L10 4
JavaScript Motivation
Scripting languages: Properties
Variables, functions, and methods
typically do not require type declarations
(automatic conversion between types, e.g. strings and numbers)
Some built-in data structures (more than in C, fewer than in Java)
Ability to generate, load, and interpret source code at run time
through an eval function
var x = 2;
var y = 6;
var str = " if ( x > 0) { y / x } else { -1 }";
con sole . log ( eval ( str )); // Output : 3
x = 0;
con sole . log ( eval ( str )); // Output : -1
COMP519 Web Programming Lecture 10 Slide L10 5
JavaScript Motivation
Scripting languages: Properties
The evolution of a scripting language typically starts
with a limited set of language constructs for a specific purpose
Example: PHP started as set of simple ‘functions’
for tracking visits to a web page
The language then accumulates more and more language constructs
as it is used for a wider range of purposes
These additional language constructs may or may not fit well together
with the original core and/or may duplicate existing language constructs
During this evolution of the language, backward compatibility
may or may not be preserved
; Language design of scripting languages is often sub-optimal
COMP519 Web Programming Lecture 10 Slide L10 6
JavaScript Overview
JavaScript
JavaScript is a language for client-side scripting
script code is embedded in a web page and
delivered to the client as part of the web page and
executed by the user’s web browser
; code is visible to the user/client
allows for better interactivity compared to server-side scripting as reaction
time is improved and data exchange with the server can be minimised
a web browser may not support JavaScript or
the user may have disallowed the execution of JavaScript code
different JavaScript engines may lead to different results, in particular,
results not anticipated by the developer of JavaScript code
performance relies on the efficiency of the JavaScript engine and
the client’s computing power
COMP519 Web Programming Lecture 10 Slide L10 7
JavaScript Overview
JavaScript
JavaScript is a language for client-side scripting
operations that refer to the location of the client are easy:
doc umen t . write (" Local time : " + (new Date ). to Stri ng ());
for security reason, scripts are limited in what they can do,
e.g. scripts cannot access the client’s filestore
COMP519 Web Programming Lecture 10 Slide L10 8
JavaScript Overview
JavaScript: History
originally developed by Brendan Eich at Netscape
under the name Mocha
first shipped together with Netscape browser in September 1995
under the name LiveScript
obtained its current name in December 1995 under a deal between
Netscape and Sun Microsystems, the company behind Java,
in December 1995
does not have a particularly close relationship to Java,
it mixes aspects of Java with aspects of other languages and its own
peculiarities
is a dialect of ECMAScript, a scripting language standardised in the
ECMA-262 specification and ISO/IEC 16262 standard since June 1997
other dialects include Microsoft’s JScript and Adobe’s ActionScript
COMP519 Web Programming Lecture 10 Slide L10 9
JavaScript Overview
JavaScript: Use
Website Client-Side Server-Side Database
Google JavaScript,
TypeScript
C, C
++
, Go, Java,
Python, PHP
BigTable, MariaDB
Facebook JavaScript Hack, PHP, Python,
C
++
, Java, . . .
MariaDB, MySQL,
HBase, Cassandra
YouTube Flash,
JavaScript
C, C
++
, Python, Java,
Go
BigTable, MariaDB
Yahoo JavaScript PHP MySQL, PostgreSQL
Amazon JavaScript Java, C
++
, Perl Oracle Database
Wikipedia JavaScript PHP, Hack MySQL, MariaDB
Twitter JavaScript C
++
, Java, Scala MySQL
Bing JavaScript C
++
, C# MS SQL Server
Wikipedia Contributors: Programming languages used in most popular websites. Wikipedia, The Free Encyclopedia,
13 September 2019, at 01:04. http://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites
[accessed 16 September 2019]
COMP519 Web Programming Lecture 10 Slide L10 10
JavaScript Example
JavaScript: Hello World!
1 <! D OCTYPE html >
2 <html ><head >< title > Hello World </ title > </ head >
3 <body >
4 <p> Our first JavaScrip t script </ p>
5 <script >
6 d ocum ent . wri teln (" <p > <b > Hello World ! </b > </p >")
7 </ script >
8 <noscript >
9 Jav aSc ript not sup por ted or dis abled
10 </ noscript >
11 </ body > </ html >
JavaScript code is enclosed in a script-element
Alternative HTML markup that is to be used in case JavaScript is not
enabled or supported by the web browser, can be specified in a
noscript-element
File must be stored in a directory accessible by the web server, for
example $HOME/public_html, and be readable by the web server
COMP519 Web Programming Lecture 10 Slide L10 11
JavaScript Scripts
JavaScript scripts
JavaScript scripts are embedded into HTML documents and are
enclosed in a script-element
A JavaScript script consists of one or more statements and comments
; there is no need for a main function (or classes)
Statements do not have to end in a semicolon but they can
; stick to one convention in your code
Whitespace before and in-between statements is irrelevant
(This does not mean it is irrelevant to someone reading your code)
One-line comments start with // and run to the end of the line
// This is a single - line comment .
Multi-line comments are enclosed in /* and */
/* This is a multi - line comm ent . The syntax could also
be used for a co mment that is only one line long . */
Comments should precede the code they are referring to
COMP519 Web Programming Lecture 10 Slide L10 12
JavaScript Type Systems and Type Checking
JavaScript: Type System
JavaScript is a dynamically and loosely typed language
All programming language provide operations that can be performed
Most programming languages provide
values (as separate from operations)
variables to store values in
user-defined operations (functions)
parameters as special kind of variables used in the definition of an operation
to refer to an argument of the operation
Most programming languages categorise values and operations
according to type
Data Type / Datatype / Type
A set of computer represented values together with a set of operations
that can be performed on those values
Value
Type
COMP519 Web Programming Lecture 10 Slide L10 13
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
Type System
A set of rules that determines the type of a value, variable, operation,
expression possibly taking into account type declarations for variables and
operations
Type Error
A failure of a type system to determine the type of a value, variable,
operation, expression
Type Checking
The process of checking that a ‘program’ complies with the type system of
its language
COMP519 Web Programming Lecture 10 Slide L10 14
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
JavaScript is a dynamically and loosely typed language
Statically typed programming language
Type checking is performed before program execution, e.g., by a compiler
Dynamically typed programming language
Type checking is performed during program execution when statements
are executed / expressions are evaluated
Strongly typed programming language
Each value has exactly one type and operations can only be applied to
argument values of the correct type
Loosely/Weakly typed programming language
A value of one type can be treated as being of another type
(or is automatically converted to the type required by an operation)
COMP519 Web Programming Lecture 10 Slide L10 15
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
Statically typed programming language
Type checking is performed before program execution, e.g., by a compiler
Example: Java is a statically typed programming language
im port java . io .*;
pu blic class TEE {
pu blic st atic void f () {
Sy stem . out , print l n (" Calle d f ()");
Sy stem . out . pr i ntln ( "0" / 1 );
}
pu blic st atic void main ( String [] args ) { }
}
javac TEE . java
TEE . java :6: e rror : bad ope r and ty pes for bin ary opera t o r ’/
Sy stem . out . pr i ntln ( "0" / 1 );
^
first type : String , secon d type : int
The compiler indicates a type error before program execution
COMP519 Web Programming Lecture 10 Slide L10 16
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
Dynamically typed programming language
Type checking is performed during program execution when statements
are executed / expressions are evaluated
Example: Python is a dynamically typed programming language
def f ():
print (" Called f ()");
print ( "0" / 1 );
py thon TEE . py
No out pu t
No e r r o r m essa ges
Expression "0" / 1, that contains a type error, is never executed,
so no error is indicated
COMP519 Web Programming Lecture 10 Slide L10 17
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
Dynamically typed programming language
Type checking is performed during program execution when statements
are executed / expressions are evaluated
Example: Python is a dynamically typed programming language
def f ():
print (" Called f ()");
print ( "0" / 1 );
f ();
py thon TEE . py
C a l l e d f ()
Tra ce back ( most r e c e n t c a l l l a s t ) :
F i l e ”TEE. py , l i n e 5 , i n <module>
f ( ) ;
F i l e ”TEE. py , l i n e 3 , i n f
p r i n t (0 / 1 ) ;
Ty pe Err or : u ns up po rt e d ope r and ty pe ( s ) f o r / : s t r and i n t
Now that Python attempts to evaluate "0" / 1, a type error is indicated
COMP519 Web Programming Lecture 10 Slide L10 18
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
Strongly typed programming language
Each value has exactly one type and operations can only be applied to
argument values of the correct type
Example: Java is a (fairly) strongly typed programming language
pu blic class STE {
pu blic st atic void main ( String [] args ) {
do uble x = 2.1 + (5 * I nteger . pa r s eInt ("2") ) ;
do uble y = 2.1 + (5 * "2");
}
}
javac STE . java
STE . java :4: e rror : bad ope r and ty pes for bin ary opera t o r ’*
do uble y = 2.1 + (5 * "2");
^
first type : int
se cond type : String
Applying arithmetic multiplication to a string is a type error
COMP519 Web Programming Lecture 10 Slide L10 19
JavaScript Type Systems and Type Checking
Type Systems and Type Checking
Loosely/Weakly typed programming language
A value of one type can be treated as being of another type
(or is automatically converted to the type required by an operation)
Example: JavaScript is a loosely typed programming language
y = 2.1 + (5 * "2 ")
co n s ole . log (y )
node STE . js
12.1
Applying arithmetic multiplication to a string works
COMP519 Web Programming Lecture 10 Slide L10 20
JavaScript Type Systems and Type Checking
JavaScript: Type System
There are types and each value is of a particular type (or none)
519 and 1.9e3 are of type number (and only of that type)
’519’ and "1.9e3" are of type string (and only of that type)
But the type of a variable does not need to be declared
var x; // d ecla res the vari able x
The type of a variable depends on the value it currently stores qnd
the type can change if it is assigned a value of a different type
x = 519; // x is of type nu mber
x = 519 ; // x is of type string
Function declarations do not specify the type of their parameters
In function applications the types of arguments will be adjusted
automatically (if possible)
COMP519 Web Programming Lecture 10 Slide L10 21
JavaScript Type Systems and Type Checking
JavaScript: Type System
There are types and each value is of a particular type (or none)
But the type of a variable does not need to be declared
The type of a variable depends on the value it currently stores and
the type can change if it is assigned a value of a different type
Function declarations do not specify the type of their parameters
fun ctio n add (x ,y) { r eturn x + y; }
In function applications the types of arguments will be adjusted
automatically (if possible)
add (519 , 1.9 e3 ) // re turns the number 2419 = 519 +190 0
add ( 519 ,"1.9 e3 ") // returns the string 5191.9 e3
add (519 , 1.9 e3 ) // re turns the string 5191.9 e3
add ( true , 1.9 e3 ) // ret urns the nu mber 1901
; makes programming easier
; potentially leads to more bugs
COMP519 Web Programming Lecture 10 Slide L10 22
Further Reading
Revision and Further Reading
Read
Chapter 14: Exploring JavaScript
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Chapter 1: What is JavaScript?
Chapter 2: JavaScript in HTML
Chapter 3: Language Basics: Syntax
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 10 Slide L10 23