COMP284 Scripting Languages
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
2 Types and Variables
Numbers
Booleans
Strings
Variables
Typecasting
Comparisons
COMP284 Scripting Languages Lecture 10 Slide L10 1
JavaScript Motivation
JavaScript: Motivation
PHP allows us to create dynamic web pages
In web applications, PHP code is executed on the web server
(server-side scripting)
allows to use a website template that is instantiated using data stored in a
database
‘business logic’ is hidden from the user:
the code of an application is not visible to the user/client;
the user/client only has access to the HTML produced by the code
not ideal for interactive web applications:
too slow to react and too much data needs to be transferred
operations that refer to the location of the user/client are difficult,
for example, displaying the local time
echo date ( 'H :i l , j F Y ' );
displays the local time on the server not the local time for the user
COMP284 Scripting Languages Lecture 10 Slide L10 2
JavaScript Overview
JavaScript
JavaScript is a language for client-side scripting
script code is embedded in a web page (as for PHP),
but 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 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 (not the server’s)
operations that refer to the location of the client are easy:
docume nt . write ( " Local time : " + ( new Date ). toS tring ());
COMP284 Scripting Languages Lecture 10 Slide L10 3
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 PHP and Perl
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 TypeScript and
Adobe’s ActionScript
COMP284 Scripting Languages Lecture 10 Slide L10 4
JavaScript Overview
Websites and Programming Languages
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 MariaDB
Twitter JavaScript C++, Java, Scala, Ruby MySQL
Bing JavaScript C++, C# MS SQL Server
Wikipedia Contributors: Programming languages used in most popular websites. Wikipedia, The Free Encyclopedia,
11 December 2019, at 16:24. https://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites
[accessed 21 December 2019]
COMP284 Scripting Languages Lecture 10 Slide L10 5
JavaScript Example
JavaScript: Hello World!
<! DOC TYPE html >
< html lang = 'en - GB ' >< head >< title > Hello World </ title > </ head >
<body >
<p > Our first Jav aS crip t script </p >
<script >
docume nt . wri teln ( " <p ><b > Hello World ! </b > </p >")
</ script >
< noscript > Ja va Scri pt not s upported or disabled </ noscript >
</ body > </ html >
JavaScript code is enclosed between <script> and </script>
Alternative HTML markup that is to be used in case JavaScript is not
enabled or supported by the web browser, can be specified between
<noscript> and </noscript>
File must be stored in a directory accessible by the web server, for
example $HOME/public_html, and be readable by the web server
No particular file name extension is required
COMP284 Scripting Languages Lecture 10 Slide L10 6
JavaScript Example
JavaScript scripts
JavaScript scripts are embedded into HTML documents and are
enclosed between <script> and </script> tags
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 semi-colon 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 commen t .
Multi-line comments are enclosed in /* and */
/* This is a multi - line co mment . The syntax could also
be used for a comm ent that is only one line long . */
Comments should precede the code they are referring to
COMP284 Scripting Languages Lecture 10 Slide L10 7
Types and Variables
Types
JavaScript is a dynamically and loosely typed language
like PHP
JavaScript distinguishes five main types:
boolean booleans
number integers and floating-point numbers
string strings
function functions
object objects (including arrays)
JavaScript distinguishes between these five types including between the
three primitive types boolean, number and string
Every value is of a particular type
Integers, floating-point numbers, and strings do not differ significantly
from the corresponding PHP types
COMP284 Scripting Languages Lecture 10 Slide L10 8
Types and Variables Numbers
Integers and Floating-point numbers
The JavaScript datatype number covers both
integer numbers 0 2012 -40 1263978
floating-point numbers 1.25 256.0 -12e19 2.4e-10
The Math object provides a wide range of mathematical functions
Math.abs(number) absolute value
Math.ceil(number) round fractions up
Math.floor(number) round fractions down
Math.round(number) round fractions
Math.log(number) natural logarithm
Math.random() random number between 0 and 1
Math.sqrt(number) square root
Math.pow(base,e) exponentiation
There are also some pre-defined number constants including
Math.PI (case sensitive) 3.14159265358979323846
NaN (case sensitive) ‘not a number’
Infinity (case sensitive) ‘infinity’
COMP284 Scripting Languages Lecture 10 Slide L10 9
Types and Variables Numbers
Numbers: NaN and Infinity
The constants NaN and Infinity are used as return values for
applications of mathematical functions that do not return a number
Math.log(0) returns -Infinity (negative ‘infinity’)
Math.sqrt(-1) returns NaN (‘not a number’)
1/0 returns Infinity (positive ‘infinity’)
0/0 returns NaN (‘not a number’)
In contrast to PHP, none of these operations causes a warning or error
JavaScript provides two functions to test whether a value is or is not
NaN, Infinity or -Infinity:
bool isNaN(value)
returns TRUE iff value is NaN
bool isFinite(value)
returns TRUE iff value is neither NaN nor Infinity/-Infinity
There is no isInfinite function
COMP284 Scripting Languages Lecture 10 Slide L10 10
Types and Variables Booleans
Booleans
JavaScript has a boolean datatype
with constants true and false (case sensitive)
JavaScript offers the same short-circuit boolean operators
as Java and PHP:
&& (conjunction) || (disjunction) ! (negation)
But and and or cannot be used instead of && and ||, respectively
The truth tables for these operators are the same as for PHP, taking
into account that the conversion of non-boolean values to boolean
values differs
Remember that && and || are not commutative, that is,
(A && B) is not the same as (B && A)
(A || B) is not the same as (B || A)
COMP284 Scripting Languages Lecture 10 Slide L10 11
Types and Variables Strings
Strings
JavaScript supports both single-quoted and double-quoted strings
JavaScript uses + for string concatenation
Within double-quoted strings JavaScript supports the following
escape characters
\b (backspace) \f (form feed) \n (newline)
\r (carriage return) \t (tab) \ (backslash)
\' (single quote) \" (double quote)
JavaScript does not support variable interpolation
JavaScript also does not support heredocs,
but multi-line strings are possible
docume nt . wri teln ( " Your name is " + name + " and \
you are stu dy in g " + degree + "\
at " + univ ersi ty );
In contrast to PHP we cannot omit the escape characters at the end of
each line
COMP284 Scripting Languages Lecture 10 Slide L10 12
Types and Variables Variables
Variables
JavaScript variable names do not start with a particular character
A JavaScript variable name may consist of letters, digits, the $ symbol,
and underscore, but cannot start with a digit
; you can still stick to the PHP ‘convention’ that
variable names start with a $ symbol
JavaScript variable names are case sensitive
COMP284 Scripting Languages Lecture 10 Slide L10 13
Types and Variables Variables
Variables
Variables can be declared using one of the following statements:
var variable1 , variable2 , ...
var v ariable1 = value1 , var ia ble2 = value2 , ...
The second statement also initialises the variables
Used inside a function definition, a declaration creates a local variable
(only accessible within the function)
Used outside a function definition, a declaration creates a global variable
A variable can be initialised without a declaration
by assigning a value to it:
variab le = value
Both inside and outside a function definition,
initialising an undeclared variable creates a global variable
Note: A declaration does not specify the type of a variable
only assigning a value of a certain type gives a variable a type
COMP284 Scripting Languages Lecture 10 Slide L10 14
Types and Variables Variables
Variables
In JavaScript, the use of the value of a variable that is neither declared
nor initialised will result in a reference error and script execution stops
A declared but uninitialised variable has the default value undefined
and has no specific type
JavaScript automatically converts a value to the appropriate type as
required by the operation applied to the value (type coercion)
The value undefined is converted as follows:
Type Default Type Default Type Default
bool false string 'undefined' number NaN
und ef in ed || true // result is true
und ef in ed + " -! " // res ult is " undefined -!"
und ef in ed + 1 // result is NaN
COMP284 Scripting Languages Lecture 10 Slide L10 15
Types and Variables Variables
Assignments
JavaScript uses the equality sign = for assignments
stu de nt_i d = 2 0084 63 69 ;
As in PHP, this is an assignment expression
The value of an assignment expression is the value assigned
b = (a = 0) + 1; // a has value 0 , b has value 1
JavaScript supports most of the standard binary assignment operators:
Binary assignment Equivalent assignment
var += expr var = var + expr
var -= expr var = var - expr
var *= expr var = var * expr
var /= expr var = var / expr
var %= expr var = var % expr
var **= expr var = var ** expr (not in MS IE)
MS Internet Explorer does not support the exponentiation operator **,
it only supports Math.pow
COMP284 Scripting Languages Lecture 10 Slide L10 16
Types and Variables Variables
Constants
JavaScript allows the definition of constants using
const variabl e1 = value1 , va ri ab le 2 = value2 , ...
defines one or more constants
constants follow the same scope rules as variables
Attempts to change the value of a constant
should result in a type error
const c olumn s = 10;
columns ++; // type error
However, this construct is not supported by MS Internet Explorer 6–10
and does not have the desired effect in Safari before version 5.1.7
nor Opera before version 12
COMP284 Scripting Languages Lecture 10 Slide L10 17
Types and Variables Variables
Values, Variables and Types
string typeof value
returns a string representation of the type of value
Boolean "boolean" Number "number"
String "string" Object "object"
undefined "undefined" null "object"
NaN "number" Infinity "number"
Future versions of JavaScript may have an option to change
typeof null to "null" (as in PHP)
docume nt . wri teln ( " Type of 23.0: " + type of ( 23. 0)
Type of 23.0: nu mbe r
docume nt . wri teln ( " Type of \"23 \": " + typeof ( " 23 ")
Type of " 23 ": string <br >
var a
docume nt . wri teln ( " Type of a : " + typeof ( a) + " <br > "
Type of a : undefined <br >
COMP284 Scripting Languages Lecture 10 Slide L10 18
Types and Variables Typecasting
Typecasting
JavaScript provides several ways to explicitly type cast a value
Apply an identity function of the target type to the value
"12" * 1 ; 12 !!"1" ; true
12 + "" ; "12" !!"0" ; true
false + "" ; "false" !!"" ; false
[12,[3,4]] + "" ; "12,3,4" !!1 ; true
[12,13] * 1 ; NaN
[12] * 1 ; 12
COMP284 Scripting Languages Lecture 10 Slide L10 19
Types and Variables Typecasting
Typecasting
JavaScript provides several ways to explicitly type cast a value
Wrap a value of a primitive type into an object
; JavaScript has objects Number, String, and Boolean with
unary constructors/wrappers for values of primitive types
(JavaScript does not have classes but prototypical objects)
Number("12") ; 12 Boolean("0") ; true
String(12) ; "12" Boolean(1) ; true
String(false) ; "false" Number(true) ; 1
Use parser functions parseInt or parseFloat
parseInt("12") ; 12 parseFloat("2.5") ; 2.5
parseInt("2.5") ; 2 parseFloat("2.5e1") ; 25
parseInt("E52") ; NaN parseFloat("E5.2") ; NaN
parseInt(" 42") ; 42 parseFloat(" 4.2") ; 4.2
parseInt("2014Mar") ; 2014 parseFloat("4.2end") ; 4.2
COMP284 Scripting Languages Lecture 10 Slide L10 20
Types and Variables Typecasting
Type conversion to boolean
When converting to boolean, the following values are considered false:
the boolean false itself
the number 0 (zero)
the empty string, but not the string ’0’
undefined
null
NaN
Every other value is converted to true including
Infinity
'0'
functions
objects, in particular, arrays with zero elements
COMP284 Scripting Languages Lecture 10 Slide L10 21
Types and Variables Typecasting
Typer conversion to string
When converting to a string:
NaN converts to 'NaN'
Infinity converts to 'Infinity'
true converts to 'true'
false converts to 'false'
null converts to 'null'
undefined converts to 'undefined'
; in JavaScript it is easier to print out boolean values than in PHP
COMP284 Scripting Languages Lecture 10 Slide L10 22
Types and Variables Comparisons
Comparison operators
JavaScript distinguishes between (loose) equality ==
and strict equality ===:
in the same way as PHP:
expr1 == expr2 Equal TRUE iff expr1 is equal to expr2
after type coercion
expr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2
after type coercion
When comparing a number and a string,
the string is converted to a number
When comparing with a boolean,
the boolean is converted to 1 if true and to 0 if false
If an object is compared with a number or string, JavaScript uses the
valueOf and toString methods of the objects to produce a primitive
value for the object
If two objects are compared,
then the equality test is true only if both refer to the same object
COMP284 Scripting Languages Lecture 10 Slide L10 23
Types and Variables Comparisons
Comparison operators
JavaScript distinguishes between (loose) equality ==
and strict equality ===:
in the same way as PHP:
expr1 === expr2 Strictly equal TRUE iff expr1 is equal to expr2,
and they are of the same type
expr1 !== expr2 Strictly not
equal
TRUE iff expr1 is not equal to expr2,
or they are not of the same type
"123" == 123 ; true "123" === 123 ; false
"123" != 123 ; false "123" !== 123 ; true
"1.23e2" == 123 ; true 1.23e2 === 123 ; true
"1.23e2" == "12.3e1" ; false "1.23e2" === "12.3e1" ; false
5 == true ; false 5 === true ; false
COMP284 Scripting Languages Lecture 10 Slide L10 24
Types and Variables Comparisons
Comparison operators
JavaScript’s comparison operators also applies type coercion to their
operands and do so following the same rules as equality ==:
expr1 < expr2 Less than true iff expr1 is strictly less than expr2
after type coercion
expr1 > expr2 Greater than true iff expr1 is strictly greater than expr2
after type coercion
expr1 <= expr2 Less than
or equal to
true iff expr1 is less than or equal to expr2
after type coercion
expr1 >= expr2 Greater than
or equal to
true iff expr1 is greater than or equal to expr2
after type coercion
'35.5' > 35 ; true '35.5' >= 35 ; true
'ABD' > 'ABC' ; true 'ABD' >= 'ABC' ; true
'1.23e2' > '12.3e1' ; false '1.23e2' >= '12.3e1' ; false
"F1" < "G0" ; true "F1" <= "G0" ; true
true > false ; true true >= false ; true
5 > true ; true 5 >= true ; true
COMP284 Scripting Languages Lecture 10 Slide L10 25
Types and Variables Comparisons
Equality and comparison operators on Infinity and NaN
Equality and comparison operators produce the following results
for Infinity and NaN:
NaN == NaN ; false NaN === NaN ; false
Infinity == Infinity ; true Infinity === Infinity ; true
NaN == 1 ; false Infinity == 1 ; false
NaN < NaN ; false Infinity < Infinity ; false
1 < Infinity ; true 1 < NaN ; false
Infinity < 1 ; false NaN < 1 ; false
NaN < Infinity ; false Infinity < NaN ; false
COMP284 Scripting Languages Lecture 10 Slide L10 26
Types and Variables Comparisons
Equality and program behaviour
Why do we care whether (5 == true) is true or false?
; it influences how our scripts behave
; it influences whether more complex objects are equal or not
PHP:
if (5) print ("5 is true " );
else print ( "5 is not true " );
print ( " and " );
if (5 == true ) print ( "5 is equal to true " );
else print ( "5 is not equal to true " );
5 is true and 5 is equal to true
JavaScript:
if (5) document . wri teln ( "5 is true " );
else docum en t . writ eln ("5 is not true " )
docume nt . wri teln ( " and ")
if (5 == true ) do cu me nt . writ el n ("5 is equal to true " )
else docum en t . writ eln ("5 is not equal to true " )
5 is true and 5 is not equal to true
COMP284 Scripting Languages Lecture 10 Slide L10 27
Types and Variables Comparisons
Equality and program behaviour
Why do we care whether (5 == true) is true or false?
; it influences how our scripts behave
; it influences whether more complex objects are equal or not
PHP:
$arr ay3 = array ( " 1.23 e2 " ,5);
$arr ay4 = array ( " 12.3 e1 " , true );
if (( $arra y3 [0] == $ ar ray 4 [0]) && ( $ a rray3 [1] == $arr ay4 [1]))
print ( " The two arrays are equal ");
else print ( " The two arr ays are not equal " );
The two array s are eq ual
JavaScript:
$arr ay3 = [" 1.23 e2 " ,5]
$arr ay4 = [" 12.3 e1 " ,true ]
if (( $arra y3 [0] == $ ar ray 4 [0]) && ( $ a rray3 [1] == $arr ay4 [1]))
docume nt . wri teln ( " The two arrays are equal " )
else docum en t . writ eln (" The two array s are not equal " )
The two array s are not equal
COMP284 Scripting Languages Lecture 10 Slide L10 28
Types and Variables Comparisons
Equality
Note: The way in which more complex data structures are compared
also differs between PHP and JavaScript
PHP:
$arr ay3 = array ( " 1.23 e2 " ,5);
$arr ay4 = array ( " 12.3 e1 " , true );
if ( $ ar ray3 == $ a rr ay4 )
print ( " The two arrays are equal " );
else print ( " The two array s are not equal ");
The two array s are eq ual
JavaScript:
$arr ay3 = [" 1.23 e2 " ,5]
$arr ay5 = [" 1.23 e2 " ,5]
if ( $ ar ray3 == $ a rr ay5 )
docume nt . wri teln ( " The two a rrays are equal " )
else docum en t . writ eln (" The two arrays are not equal " )
The two array s are not equal
COMP284 Scripting Languages Lecture 10 Slide L10 29
Revision
Revision
Read
Chapter 13: Exploring JavaScript
of
R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
COMP284 Scripting Languages Lecture 10 Slide L10 30