SlideShare a Scribd company logo
1 of 106
Download to read offline
Client-side scripting
Eleonora Ciceri
ciceri@elet.polimi.it
Scripts
¤  “A script is a program that automates the execution of
tasks which could alternatively be executed one-by-one
by a human operator”
¤  Where to use scripts?
¤  Software applications
¤  Web pages
¤  Shells of operating systems
¤  …
Scripts: characteristics
Programmer
ü  Low writing complexity
ü  A few lines of code
Execution
ü  Integration with automatic
system configuration (e.g.,
execute on startup)
ü  Absence of graphical interface
ü  Call other programs if more
complex stuff execution is
required
Scripting languages
¤  A scripting language is a programming language that
supports the writing of scripts
¤  Characteristics
¤  Ease of use: scripting languages are intended to be very fast
to pick up and author programs in
¤  OS facilities: built in with easy interfaces
¤  Interpreted from source code: to give the fastest turnaround
between the scripting phase and the execution phase
Examples of scripting languages
¤  Shell: bash, sh
¤  GUI scripting
¤  Application-specific: e.g., text processing with perl and
XSLT
¤  General purpose: Groovy, Perl, Python, Ruby
¤  Web:
¤  Server-side
¤  Client-side: JavaScript, VBScript
Interpreter vs. Compiler
Interpreter
¤  Source code is executed
directly, line by line
Compiler
¤  Source code is transformed
into binary code
(executable file)
Comparison: software code
The software code
is written by the
programmer…
… then
compiled.
Errors make the
code return to
the programmer
for further refining
A successful
compilation
process produces
machine code
The executable file is
distributed to the user, who
does not access to the code
¤  Scripts have different usages…
¤  Scripts are created and/or modified by the person who
executes them
¤  A script is used in order to extend application functionalities,
or to execute simple tasks by using pre-existing components
Comparison: scripts
The script is written
by the
programmer…
… then, neither
compiling phase
nor linking phase
are executed
Each line is
interpreted, from the
top to the bottom
An error makes the
procedure fail
If the execution is ok,
the user can see the
output
Server-side scripting
¤  The server-side scripting comprises all the scripts that are
executed on the server
¤  Adopted technologies: Perl, PHP, Coldfusion, XSTL…
¤  The code is not visible to the client
¤  The client receives just the HTML code!
The script is written
by the
programmer…
… then it is
uploaded on the
server REQUEST
The HTML code is
generated by parsing
the script page
The user receives just the
HTML code (the script
code is NOT visible)
Client-side scripting
¤  The client-side scripting comprises all the scripts that are
executed on the browser
¤  This scripting derives from the event-based programming
that is typical of user interfaces
¤  Adopted technologies: Javascript, Vbscript
Client-side scripting
¤  The scripts are downloaded by browsers:
¤  Either as a part of an HTML page
¤  Or from external resources linked by a page and retrieved
using the HTTP protocol
The script is
injected in the
HTML code REQUEST
The user receives the
script; the script code IS
visible
Client-side scripting
¤  The HTML page functionalities are extended, adding a
behaviour to it
¤  Examples of added behaviours:
¤  Page updates answering to an user event / a system event
The user clicks
on a button
The browser looks for
the part of script
related to the “click
on button” event
If the function is
not present, the
page does not
react
If the function is present, the
page reacts to the event by
applying the suggested
behavior
Client-side scripting evolution
¤  Past use
¤  Animations of images and menus (e.g., onMouseOver)
¤  Simple widgets (e.g., clock, calendar)
¤  Form validation
¤  Present use
¤  AJAX: Asynchronous JavaScript And XML
¤  Reactive interfaces (similar to desktop applications)
¤  Asynchronous communication between client and server
¤  Separation of computation between client and server
¤  Communication effort reduced
Standards
Standards: HTML scripting
¤  The HTML scripting is part of the HTML4 recommendation,
and it defines:
¤  Where the scripts can be inserted in the HTML markup
¤  Which events control the execution of a script (e.g., events
of loading a document or click on a button)
¤  The HTTP protocol functionalities are exploited for
retrieving scripts
Standards: DOM
The DOM (Document Object
Model) is an object oriented
model for representing HTML
and XML documents
JavaScript
Main concepts
JavaScript
¤  JavaScript is the language of the web browser
¤  Good parts
¤  Functions are objects
¤  Dynamic objects (“Want to add another property? Do it!”)
¤  Loose typing
¤  Bad parts
¤  Model based on global variables
JavaScript vs. Java
¤  Java and JavaScript share just similarities on the name!
¤  JavaScript is a scripting language
¤  Interpreted
¤  Uses the browser for the input/output procedures
¤  Loose typing
¤  Nothing to be installed (interpreted by the browser, natively)
¤  Java is a programming language
¤  Compiled in bytecode; executed on a virtual machine
¤  Strong typing
¤  Used as a standalone program or as an applet
An example: Fibonacci (1)
<html>!
<head>!
!<title>Fibonacci series</title>!
!<script language="JavaScript"> !!
...script...!
!</script>!
</head>!
<body>!
<button
onclick="computeFibonacciSeries()">Compute
Fibonacci Series</button>!
!<div id="content"></div>!
</body>!
</html>
The results are stored here
An example: Fibonacci (2)
function computeFibonacciSeries() {!
!var contentDiv = document.getElementById("content");!
!var header = document.createElement("h3");!
!header.appendChild(document.createTextNode("Fibonacci series:"));!
!contentDiv.appendChild(header);!
! ! ! !!
!var first = 0, second = 1, temp; !
!for(i=1; i<10; i++) { !
temp = first + second; !
contentDiv.appendChild(document.createTextNode(first));!
contentDiv.appendChild(document.createElement("br")); !
first = second; !
second = temp; !
!}!
};!
Retrieve the
reference to
the div
Store the computed
number in the content div
JavaScript
Grammar
Grammar: Whitespaces and
comments
¤  Whitespace
¤  It can take the form of formatting characters or comments
¤  It is necessary to use whitespace to separate sequences of
characters that would be combined into a single token
¤  var that = this;!
¤  Comments
¤  // This is a comment on a line!
¤  /* This is a comment that can be written in
multiple lines */!
Grammar: Names
¤  A name is a letter optionally followed by one or more
letters, digits or underbars
¤  Reserved words: abstract, boolean, break, byte, case,
catch, char, class, const, continue, debugger,
default, delete, do, double, else, enum, export,
extends, false, final, finally, float, for, function,
goto, if, implements, import, in, instanceof, int,
interface, long, native, new, null, package, private,
protected, public, return, short, static, super,
switch, synchronized, this, throw, throws,
transient, true, try, typeof, var, volatile, void,
while, with!
Grammar: Numbers
¤  JavaScript has a single number type (64-bit floating point,
the same as Java double)
¤  No separate integer type (1 and 1.0 are the same)
¤  Exponents: 100 = 1e2
¤  Negative numbers are formed by using the – prefix operator
¤  Special numbers
¤  NaN is the result of an operation that cannot produce a normal
result
¤  Infinity represents the infinity value
¤  The Math object contains a set of methods that act on
numbers
Grammar: Strings
¤  A string can be wrapped in single or double quotes
¤  The char type is not present (use a string containing just one
character!)
¤  The “” is the escape character
¤  The length property is used to compute the string length
¤  “seven”.length = 5
¤  Strings are immutable, i.e., once they are made, they can
never be changed
¤  New strings can be created by concatenating other strings with
the + operator
Grammar: Statements
¤  Each <script> tag delivers a compilation unit that is
compiled and immediately executed
¤  Statements are executed from top to bottom
¤  The sequence of execution can be altered by the
conditional statements (if and switch), by the looping
statements (while, for and do) and by the disruptive
statements (break, return and throw)
¤  A block is a set of statements wrapped in curly braces
¤  Blocks do not create a new scope: variables have to be
defined at the top of the function, not in blocks
Grammar: if statement
¤  if (expression) then {block} else {block}!
¤  False values
¤  False, null, undefined, ‘’, 0, NaN
¤  True values
¤  All the other values
Grammar: for statement
¤  for (initialization; condition; increment)
{block}!
¤  If the condition is false, the loop breaks
¤  Otherwise, the block is executed, the increment executes,
and the loop repeats with the condition
¤  for (variable in object) {block}!
¤  Enumeration of the property names of an object
¤  On each iteration, the current property name is assigned to
the variable
Grammar: try, catch, throw (1)
¤  The try statement executes a block and catches any
exceptions that were thrown by the block
¤  The catch clause defines a new variable that will receive
the exception object
¤  The throw statement raises an exception
¤  It throw is in the try block, the control goes to catch!
¤  In throw is not in the try block, the function is abandoned,
and the control goes to the catch clause of the try in the
calling function
Grammar: try, catch, throw (2)
Example of throw
var add = function(a,b) {!
if (typeof a !== ‘number’ || typeof b !== ‘number’) {!
throw {!
name: ‘TypeError’,!
message: ‘add function needs numbers’!
};!
}!
return a + b;!
}!
Grammar: try, catch, throw (3)
Example of try/catch
var try_it = function() {!
!try {!
! !add(“seven”);!
!}!
!catch (e) {!
! !document.writeln(e.name + “: “ + e.message);!
!}!
}!
Grammar: return, break!
¤  The return statement causes the early return from a
function
¤  A return value can be specified
¤  If the return value is not specified, the return value will be
undefined
¤  The break statement causes the exit from a loop
statement or a switch statement
Grammar: other statements
¤  An expression statement can:
¤  Assign values to one or more variables or members
¤  Invoke a method
¤  Delete a property from an object
¤  The = operator is used for assignment
¤  The === / == operator is the equality operator
¤  ===: equality for both the value and the type
¤  ==: equality for the value
¤  The += operator can add or concatenate
Operators
Operators Meaning
. [] ()! Refinement and invocation
delete new typeof + - !! Unary operators
* / %! Multiplication, division, modulo
+ -! Addition/concatenation,
subtraction
>= <= > <! Inequality
=== !== == !=! Equality
&&! Logical AND
||! Logical OR
?:! Ternary
Prefix operators
¤  Typeof
¤  ‘number’, ‘string’, ‘boolean’, ‘undefined’, ‘function’, and
‘object’
Operators Meaning
!! Logical not
+! Add or concatenate
-! Negate
Loose typing vs. Strong typing
¤  Most programming languages demand strong typing
¤  Pro: you can detect errors at compile time
¤  Cons: casting between different types
¤  JavaScript is a loosely typed programming language
¤  Pro: no casting between different types
¤  Cons: you cannot understand whether there are errors until
you execute the code
Javascript: part 2
Eleonora Ciceri
Ph.D. student – Politecnico di Milano
eleonora.ciceri@polimi.it
JavaScript
Objects
Java: what is an object?
¤  A class defines the data type and allows the creation of
objects
¤  The object characteristics reflect the ones required by the
class definition
maxSpeed doors
color
myCar = new Car();!
myCar adheres to the schema
defined when the class was
declared
There is not the possibility to extend
the object by adding and/or
removing attributes/methods
JavaScript: what is an object?
¤  Well, everything is an object
¤  “Objects are class-free containers used for collecting and
organizing data”
¤  Moreover, you can define your own objects
Simple data types
(Either used as primitive data
or objects)
ü  Booleans
ü  Numbers
ü  Strings
Complex data
types
ü  Dates
ü  Arrays
ü  Functions
How to build JavaScript objects
¤  Definition: an object is a special kind of data with:
¤  Properties: the values associated with an object
¤  Methods: the actions that can be performed on an object
¤  How to access to an object?
Property
objectName.propertyName!
Method
objectName.methodName()
car.color! car.run()!
Creating JavaScript objects:
Create a direct instance
¤  It is possible to create an object on the fly, by adding
properties to it
¤  Translated:
1.  Create an empty object
2.  Add the firstName property with value John!
3.  …
person = new Object();!
person.firstName = “John”;!
person.lastName = “Doe”;!
person.age = 50;!
person.eyeColor = “blue”;!
Creating JavaScript objects:
Create a direct instance
¤  Every time a property is added to the definition, the
object schema is expanded to contain the new property
¤  This suggests that JavaScript objects are flexible and not
tied to a given schema
¤  JavaScript objects are class-free
person.firstName!
person.firstName!
person.lastName!
person.firstName!
person.lastName!
person.age!
Creating JavaScript objects:
Create an object literal
¤  An object literal is a pair of curly braces surrounding zero
or more name/value pairs
¤  This equals to add properties one at a time to the object
var empty_object = {};!
var employee = {!
“first-name”: “Jerome”,!
“last-name”: “Howard”!
};!
Creating JavaScript objects:
Use an object constructor
¤  Here comes the this reference:
¤  We are going to handle more than one person at a time
¤  Which person we are dealing must be clear
¤  this indicates the instance of object at hand
function person(firstName, lastName, age, eyeColor) {!
this.firstName = firstName;!
this.lastName = lastName;!
this.age = age;!
this.eyeColor = color;!
}!
Creating JavaScript objects:
Use an object constructor
¤  Once you have a new constructor, you can create an
object instance:
¤  The constructor automatically fills the properties by using
the values that are passed as parameters
var myFather = new person(“John”,”Doe”,50,”blue”);!
Add properties anywhere, anytime
¤  When an object has been created, you can decide to
add new properties at each point of your script
¤  The object keeps updating itself every time an expansion
is required
object = new Object();!
object.myProperty = “MyProperty”;!
[do some stuff]!
[do some other stuff]!
object.mySecondProperty = “MySecondProperty”;!
[do more and more stuff]!
object.myThirdProperty = “MyThirdProperty”;!
Adding methods to JavaScript
objects
¤  Methods are just functions attached to objects
¤  Their definition is done inside the object constructor function
function person(firstName, lastName, age, eyeColor){!
this.firstName = firstName;!
this.lastName = lastName;!
this.age = age;!
this.eyeColor = eyeColor;!
this.changeName = changeName;!
function changeName(name) {!
this.lastName = name;!
}!
} !
Adding methods to JavaScript
objects
¤  This just expands the object, as in the case of the
properties
¤  The only difference is that methods are functions, so they
manipulate data rather than adding new fields
¤  The function can be then called on the object:
¤  myMother.changeName(“Doe”);!
person.firstName!
person.lastName!
person.age!
person.changeName()!
Object prototype
¤  Every object is linked to a prototype object from which it
can inherit properties
¤  Object are linked to Object.prototype, an object that
comes standard with JavaScript
¤  The prototype link has no effect on updating
¤  Changes to an object do not affect the object’s prototype
¤  The prototype is dynamic
¤  If we add a new property to the prototype, it will be visible in
all the objects that are based on the prototype
Object prototype
Not here? Retry
with its prototype
Not here? Retry
with its prototype
… Returns property
Returns undefined!
Reading properties:
Inspection
¤  We have seen that this retrieves a property:
person.firstName!
¤  This retrieves exactly the same property:
person[firstName]!
¤  And this too:
person[“firstName”]!
Reading properties:
Inspection
¤  So, how to select the appropriate access method?
¤  The quotes are required for names that :
¤  Correspond to reserved words
¤  Contain special characters (e.g., -, _, whitespaces)
¤  The dot notation usage depends on quotes:
¤  Can be used if the property name does not require quotes
(but this is not strictly necessary)
¤  Cannot be used if the property name require quotes; in this
case, go for []
Reading properties:
Inspection
¤  We have seen that this returns a property:
person[“firstName”]!
¤  We have also seen that strings can be declared either
using single quotes or using double quotes
¤  Since the property name is in this case a string, the
following returns exactly the same property:
person[‘firstName’]!
Reading properties:
Inspection
¤  The typeof operator reads the property type
¤  The values can correspond either to data or to functions
¤  typeof person.toString returns ‘function’
¤  The hasOwnProperty method returns true if the object
has that particular property, without looking at the
prototype chain
Reading properties:
Enumeration
¤  Now the iteration over the object properties should be
clear…
¤  Which is the output?
var person = {firstName:”John”, lastName:”Doe”};!
text = “”;!
for (property in person) {!
text = text + person[property] + “ “;!
}!
Reading properties:
Enumeration
¤  Now the iteration over the object properties should be
clear…
¤  Which is the output?
¤  N.B. The order in which the properties are printed is not
guaranteed
var person = {firstName:”John”, lastName:”Doe”};!
text = “”;!
for (property in person) {!
text = text + person[property] + “ “;!
}!
John Doe
Reading non-existing properties
¤  What if we try to access to person.numChildren?
¤  Remember? We didn’t define its value
¤  Yet another difference between Java and JavaScript:
¤  Java: not working
¤  JavaScript: if the value is not defined, and the undefined
value is defined:
¤  Since this is not so nice to be handled, we can modify to:
¤  var middle = employee[“middle-name”] || “(none)”;!
person.numChildren returns undefined !
Reading undefined!
¤  Be really careful: don’t try to access to the internals of
undefined!
¤  Attempting to retrieve values from undefined will throw a
TypeError exception
undefined
TypeError
Update object properties
¤  If the property already exists, it is replaced:
¤  person[‘firstName’] = ‘John’;!
¤  If the object does not already have that property name,
the object is augmented:
¤  person[‘nickname’] = ‘Curly’;!
Delete object property
¤  The delete operator removes a property from an object
¤  delete person.nickname!
¤  If a property can’t be deleted, the operation returns false!
¤  N.B. Variables cannot be deleted…
¤  var x = 1;!
¤  delete x; // false!
¤  …and neither can be functions:
¤  function x() {}!
¤  delete x; // false!
Object references
¤  Objects are passed around by reference (never copied!)
person.name = ‘John’;!
var x = person;!
x.name = ‘Sam’;!
var name = person.name! ‘John’
person
Object references
¤  Objects are passed around by reference (never copied!)
person.name = ‘John’;!
var x = person;!
x.name = ‘Sam’;!
var name = person.name! ‘John’
person
x
Object references
¤  Objects are passed around by reference (never copied!)
person.name = ‘John’;!
var x = person;!
x.name = ‘Sam’;!
var name = person.name! ‘Sam’
person
x
Object references
¤  Objects are passed around by reference (never copied!)
!
¤  name is ‘Sam’ because x and person are references to
the same object
person.name = ‘John’;!
var x = person;!
x.name = ‘Sam’;!
var name = person.name! ‘Sam’
person
x
name
Object references
¤  var a={}, b={}, c={}!
¤  a, b and c refer to different empty objects
¤  var a = b = c = {}!
¤  a, b and c all refer to the same empty object
a b c
a b
c
Global objects
¤  All the top-level variables of all compilation units are
tossed together in a common namespace called the
global object
¤  Needed because: global variables can hold all of the assets
of an application
¤  Disadvantage: they increase the possibility that different
applications interact badly together, “stealing” other
applications’ variables
Global objects
¤  Solution: usage of a single global variable!
var MYAPP = {};!
MYAPP.employee = {!
“first-name”: “John”,!
“last-name”: “Doe”!
};!
¤  Advantages
¤  Reduce the chance of bad interactions with other
applications, widgets or libraries
¤  Enhanced readability of the program
JavaScript
Functions
Functions
¤  What is a function?
¤  A block of code that encloses a set of statements
¤  An object
¤  Why do we use functions?
¤  Code reuse
¤  Information hiding
¤  Composition
Functions
¤  Since functions are objects, they can be:
¤  Stored in variables, objects and arrays
¤  Passed as arguments to functions
¤  Returned as the result of a function
¤  Functions can have properties and methods
Functions that return a function
¤  A function can return another function as return value
¤  There is a really important difference:
¤  Assigning a variable to a function (without the parenthesis)
copies the reference to the function
¤  Putting the parenthesis at the end of a function name calls
the function and returns the function return value
Functions that return a function
function a() {!
alert('A');!
}!
//alerts 'A', returns undefined!
!
function b() {!
alert('B');!
return a;!
}!
//alerts 'B', returns function a!
!
function c() {!
alert('C');!
return a();!
}!
//alerts 'C', alerts 'A', returns undefined!
!
alert("Function 'a' returns " + a());!
alert("Function 'b' returns " + b());!
alert("Function 'c' returns " + c());!
Function closure
¤  Functions can be defined inside other functions
¤  An inner function can access to the parameters and
variables of the functions it is nested within
¤  The function object created by a function literal contains
a link to that outer context
¤  This is called closure
Function closure
Function closure
This function
can see these
variables
Closure
Function closure
This function
CANNOT see
these variables
Closure
¤  There are cases when an inner function has a longer
lifetime than its outsider function
¤  The closure is adopted to implement private variables,
getters and setters
var fade = function (node) {!
var level = 1;!
var step = function () {!
var hex = level.toString(16);!
node.style.backgroundColor = ‘#FFFF’ + hex + hex;!
if (level < 15) {!
level += 1;!
setTimeout(step,100);!
}!
};!
setTimeout(step,100);!
};!
This function can see
level, and operates on itAll these variables live
until the function
needs them; when the
function terminates,
they are deleted
Function literals
var add = function sum(a,b) {!
return a + b;!
};!
Reserved word
Function’s name (optional)
•  Used to call the function
recursively
•  If not defined, the function is said
to be anonymous
Function’s parameters
Parameters are variables in
the function, initialized with
the provided value
Function’s statements
The body of the function
executed when the
function is invoked
Scope
¤  A scope defines the visibility and the lifetime of variables
and parameters
¤  JavaScript does not have block scope
¤  All the variables defined in a block are not visible from outside
the block
¤  JavaScript has function scope
¤  Parameters and variables defined in a function are not visible
outside the function
¤  A variable defined in a function is visible in the function
¤  Inner function can access parameter and variables of the
function they are defined within
Function invocation
¤  Invoking a function suspends the current function
¤  The control is passed to the new function
¤  Parameters are passed too
¤  Passed parameters
¤  The ones specified by the user
¤  this!
Function invocation
¤  A function may be called with any number of arguments
function go(a,b) {!
alert('A=’+ a +’; B=’+ b);!
}!
go(1)!
go(1,2)!
go(1,2,3)!
a=1,b undefined
a=1,b=2
a=1,b=2, third
parameter is not listed
Function invocation:
Method Invocation Pattern
¤  Functions can be stored as properties of an object
¤  The parameter this is bound to that object
¤  It is used to refer to the object when a modification is needed
var myObject = {!
value: 0,!
increment: function (inc) {!
this.value += typeof inc === ‘number’ ? inc : 1;!
}!
};!
Function invocation:
Function Invocation Pattern
¤  There can be functions which are not properties of an
object
¤  These functions are bounded to the global object
¤  A method cannot use an inner function to help if do its work,
(the inner function does not share a reference to this)
myObject.double = function() {!
var that = this;!
var helper = function (){!
that.value = add(that.value, that.value);!
};!
helper();!
};!
To let this function
access to this, we
have to store a
reference to it in the
that variable, which is
visible in the inner
function
Function invocation:
Constructor Invocation Pattern
¤  The functions invoked with the new prefix are called
constructors
¤  When the function is called, a new object is created
¤  The object contains a link to the value of the function’s
prototype member
var Quo = function(string) {!
this.status = string;!
};!
Quo.prototype.get_status = function() {!
return this.status;!
};!
var myQuo = new Quo(“confused”);!
Constructor: this creates
an object with a
status property
Give all instances of Quo
a public method called
get_status
Create a new instance
of Quo
Function invocation:
Apply Invocation Pattern
¤  The apply method allows to
¤  Choose the value of this!
¤  Build an array of arguments to use to invoke a function
var array = {3,4};!
var sum = add.apply(null, array);!
/**********************************/!
var Quo = function (string) {!
this.status = string;!
}!
var statusObject = {!
status: ‘A-OK’;!
};!
Status = Quo.prototype.get_status.apply(statusObject);!
Create an array of two
numbers and add them
Create an object with a
status member
Constructor (see
previous slide)
The variable
Status is equal
to ‘A-OK’!
Function arguments!
¤  The arguments array is available to functions when they
are invoked
¤  The arguments array give access to all the values
supplied with the invocation
¤  It includes additional ones, not assigned to parameters
¤  It allows the definition of functions with an unspecified
number of parameters
¤  Notice that arguments is not a proper array
¤  It has the length property
¤  It lacks all the other methods
Function return!
¤  The last } in a function returns the control to the part of
the program that invoked the function
¤  The return statement can be used to cause a function
to return early
¤  A function always returns a value
¤  Undefined: if the return value is not specified, then
undefined is returned
¤  This: if the function was invoked with the new prefix, then the
return value this is returned
Callbacks
¤  A callback is useful to deal with discontinuous events
¤  A function can be passed to another function as parameter
¤  This function will be invoked asynchronously
¤  Example: AJAX requests
request = prepare_the_request();!
!
send_request_asynchronously(!
request, !
function (response) {!
display(response);!
}!
};!
JavaScript
Arrays
What is an array?
¤  An array is a linear allocation of memory in which
elements are accessed by integers that are used to
compute offsets
What is an array in JavaScript?
¤  Problem: although they are very efficient and useful,
JavaScript does not have them L
¤  Solution: JavaScript provides an object that has some
array-like features
¤  Array subscripts are converted into strings and are used as
indexes
¤  Elements in an array can contain any mixture of values
Example: array misc!
var misc = [!
‘string’, 98.6, true, false, null, undefined,
[‘nested’, ‘array’], {object: true}, NaN, Infinity!
];!
¤  If misc.length is invoked, the result 10 is retrieved
‘string’ 98.6 true false null undefined ‘nested’ {object:true} NaN Infinity
‘array’
1 2 3 4 5 6 7 8 9 10
Array literal vs. object literal (1)
var numbers = [!
‘zero’, ‘one’, ‘two’,
‘three’, ‘four’,
‘five’, ‘six’,
‘seven’, ‘eigth’,
‘nine’!
];!
var numbers_object = {!
‘0’: ‘zero’, ‘1’:
‘one’, ‘2’: ‘two’,
‘3’: ‘three’, ‘4’:
‘four’, ‘5’: ‘five’,
‘6’: ‘six’, ‘7’:
‘seven’, ‘8’: ‘eight’,
‘9’: ‘nine’!
}!
Both numbers and numbers_object are objects with 10 properties,
having the same names and values
•  numbers inherits from Array.prototype (length property, other
array methods)
•  numbers_object inherits from Object.prototype (no length
property)
Array length
¤  The length property is an upper bound
¤  When a subscript greater than the array length is used, this
increases the array length
¤  Thus, the length is the largest integer property name in the
array plus one, not the number of properties in the array!
¤  Length can be set explicitly
¤  If the length is greater than the number of properties, this
does not allocate more space for the array
¤  If the length is smaller than the number of properties, this
causes properties to be deleted
Modify arrays
¤  The delete operator can be used to remove elements
from arrays
¤  This leaves a hole in the array, since the element on the right
holds its original name
¤  delete numbers[2];!
¤  The splice method deletes some number of elements
and replace them with other elements (specified from
the third parameter)
¤  numbers.splice(2,1);!
The position from which
elements are deleted
How many elements are
deleted
Access to arrays
¤  The for…in operator can be used to iterate over arrays
¤  This works in the same way as accessing to object properties
¤  Problems
¤  No guarantee about the order of the properties
¤  Some browser drags unexpected properties from the
prototype chain
¤  Arrays in JavaScript are not initialized (thus missing elements
have an undefined value)
Matrices
¤  JavaScript does not have multi-dimensional arrays (but
one can define arrays of array)
…
JavaScript
Warnings
typeof!
¤  The typeof operator returns a string that identifies the
type of its operand
¤  Problem: typeof null returns ‘object’ instead of ‘null’
¤  typeof cannot distinguish between null and objects,
but you can because null is false and all objects are true
¤  A better test for null is: myValue === null?
Equality
¤  Equality operators are === and !==
¤  If two objects are of the same type and with the same value,
then the operator === returns true
¤  The operator == tries to compare objects of different types
‘’ == ‘0’! False
0 == ‘’! True
0 == ‘0’! True
false == ‘false’! False
false == 0! True
false == undefined! False
false == null! False
null == undefined! True
JavaScript: WAT?
¤  WAT? Video (01:20)
References
References
¤  Wikipedia, “Scripting language”
¤  JavaScript: The Good Parts, Douglas Crockford, O’Reilly
¤  http://javascript.crockford.com/ (videos!)
¤  W3C Javascript Tutorial: http://www.w3schools.com/js/
default.asp
¤  HTML.it Javascript: http://javascript.html.it/
References
¤  http://perfectionkills.com/understanding-delete/
¤  http://www.w3schools.com/js/js_objects.asp

More Related Content

What's hot (20)

HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Javascript
JavascriptJavascript
Javascript
 
New Elements & Features in HTML5
New Elements & Features in HTML5New Elements & Features in HTML5
New Elements & Features in HTML5
 
Java script
Java scriptJava script
Java script
 
Scripting Languages
Scripting LanguagesScripting Languages
Scripting Languages
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Web api
Web apiWeb api
Web api
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
Web Servers (ppt)
Web Servers (ppt)Web Servers (ppt)
Web Servers (ppt)
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
Web Development
Web DevelopmentWeb Development
Web Development
 
Introduction to Web Development
Introduction to Web DevelopmentIntroduction to Web Development
Introduction to Web Development
 
Java script
Java scriptJava script
Java script
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Web technology practical list
Web technology practical listWeb technology practical list
Web technology practical list
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 
introduction to web technology
introduction to web technologyintroduction to web technology
introduction to web technology
 

Viewers also liked (14)

Client side scripting and server side scripting
Client side scripting and server side scriptingClient side scripting and server side scripting
Client side scripting and server side scripting
 
Design Patterns: Defining and Sharing Web Design Languages
Design Patterns: Defining and Sharing Web Design Languages Design Patterns: Defining and Sharing Web Design Languages
Design Patterns: Defining and Sharing Web Design Languages
 
Client & server side scripting
Client & server side scriptingClient & server side scripting
Client & server side scripting
 
Client side and server side scripting
Client side and server side scriptingClient side and server side scripting
Client side and server side scripting
 
Server Scripting Language -PHP
Server Scripting Language -PHPServer Scripting Language -PHP
Server Scripting Language -PHP
 
06 Javascript
06 Javascript06 Javascript
06 Javascript
 
Client side scripting and server side scripting
Client side scripting and server side scriptingClient side scripting and server side scripting
Client side scripting and server side scripting
 
C5 Javascript
C5 JavascriptC5 Javascript
C5 Javascript
 
Perl
PerlPerl
Perl
 
Xhtml
XhtmlXhtml
Xhtml
 
Php Form
Php FormPhp Form
Php Form
 
Client and server side scripting
Client and server side scriptingClient and server side scripting
Client and server side scripting
 
Web Design Notes
Web Design NotesWeb Design Notes
Web Design Notes
 
Beautiful Web Design
Beautiful Web DesignBeautiful Web Design
Beautiful Web Design
 

Similar to Client side scripting

Hsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfHsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfAAFREEN SHAIKH
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch casesMeoRamos
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angelibergonio11339481
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!olracoatalub
 
Switch case and looping statement
Switch case and looping statementSwitch case and looping statement
Switch case and looping statement_jenica
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxTusharTikia
 
introduction to server-side scripting
introduction to server-side scriptingintroduction to server-side scripting
introduction to server-side scriptingAmirul Shafeeq
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping newaprilyyy
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_scriptVijay Kalyan
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxsandeshshahapur
 

Similar to Client side scripting (20)

Survelaine murillo ppt
Survelaine murillo pptSurvelaine murillo ppt
Survelaine murillo ppt
 
Hsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfHsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdf
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angeli
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Switch case and looping statement
Switch case and looping statementSwitch case and looping statement
Switch case and looping statement
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
 
introduction to server-side scripting
introduction to server-side scriptingintroduction to server-side scripting
introduction to server-side scripting
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
My final requirement
My final requirementMy final requirement
My final requirement
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Web programming
Web programmingWeb programming
Web programming
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
 

More from Eleonora Ciceri

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfEleonora Ciceri
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfEleonora Ciceri
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfEleonora Ciceri
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfEleonora Ciceri
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfEleonora Ciceri
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfEleonora Ciceri
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - ExercisesEleonora Ciceri
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorEleonora Ciceri
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch frameworkEleonora Ciceri
 

More from Eleonora Ciceri (18)

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdf
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdf
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdf
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdf
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Trees
TreesTrees
Trees
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - Exercises
 
Doubly Linked Lists
Doubly Linked ListsDoubly Linked Lists
Doubly Linked Lists
 
Linked lists
Linked listsLinked lists
Linked lists
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
HTML5 - An introduction
HTML5 - An introductionHTML5 - An introduction
HTML5 - An introduction
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User Behavior
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch framework
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Client side scripting

  • 2. Scripts ¤  “A script is a program that automates the execution of tasks which could alternatively be executed one-by-one by a human operator” ¤  Where to use scripts? ¤  Software applications ¤  Web pages ¤  Shells of operating systems ¤  …
  • 3. Scripts: characteristics Programmer ü  Low writing complexity ü  A few lines of code Execution ü  Integration with automatic system configuration (e.g., execute on startup) ü  Absence of graphical interface ü  Call other programs if more complex stuff execution is required
  • 4. Scripting languages ¤  A scripting language is a programming language that supports the writing of scripts ¤  Characteristics ¤  Ease of use: scripting languages are intended to be very fast to pick up and author programs in ¤  OS facilities: built in with easy interfaces ¤  Interpreted from source code: to give the fastest turnaround between the scripting phase and the execution phase
  • 5. Examples of scripting languages ¤  Shell: bash, sh ¤  GUI scripting ¤  Application-specific: e.g., text processing with perl and XSLT ¤  General purpose: Groovy, Perl, Python, Ruby ¤  Web: ¤  Server-side ¤  Client-side: JavaScript, VBScript
  • 6. Interpreter vs. Compiler Interpreter ¤  Source code is executed directly, line by line Compiler ¤  Source code is transformed into binary code (executable file)
  • 7. Comparison: software code The software code is written by the programmer… … then compiled. Errors make the code return to the programmer for further refining A successful compilation process produces machine code The executable file is distributed to the user, who does not access to the code
  • 8. ¤  Scripts have different usages… ¤  Scripts are created and/or modified by the person who executes them ¤  A script is used in order to extend application functionalities, or to execute simple tasks by using pre-existing components Comparison: scripts The script is written by the programmer… … then, neither compiling phase nor linking phase are executed Each line is interpreted, from the top to the bottom An error makes the procedure fail If the execution is ok, the user can see the output
  • 9. Server-side scripting ¤  The server-side scripting comprises all the scripts that are executed on the server ¤  Adopted technologies: Perl, PHP, Coldfusion, XSTL… ¤  The code is not visible to the client ¤  The client receives just the HTML code! The script is written by the programmer… … then it is uploaded on the server REQUEST The HTML code is generated by parsing the script page The user receives just the HTML code (the script code is NOT visible)
  • 10. Client-side scripting ¤  The client-side scripting comprises all the scripts that are executed on the browser ¤  This scripting derives from the event-based programming that is typical of user interfaces ¤  Adopted technologies: Javascript, Vbscript
  • 11. Client-side scripting ¤  The scripts are downloaded by browsers: ¤  Either as a part of an HTML page ¤  Or from external resources linked by a page and retrieved using the HTTP protocol The script is injected in the HTML code REQUEST The user receives the script; the script code IS visible
  • 12. Client-side scripting ¤  The HTML page functionalities are extended, adding a behaviour to it ¤  Examples of added behaviours: ¤  Page updates answering to an user event / a system event The user clicks on a button The browser looks for the part of script related to the “click on button” event If the function is not present, the page does not react If the function is present, the page reacts to the event by applying the suggested behavior
  • 13. Client-side scripting evolution ¤  Past use ¤  Animations of images and menus (e.g., onMouseOver) ¤  Simple widgets (e.g., clock, calendar) ¤  Form validation ¤  Present use ¤  AJAX: Asynchronous JavaScript And XML ¤  Reactive interfaces (similar to desktop applications) ¤  Asynchronous communication between client and server ¤  Separation of computation between client and server ¤  Communication effort reduced
  • 15. Standards: HTML scripting ¤  The HTML scripting is part of the HTML4 recommendation, and it defines: ¤  Where the scripts can be inserted in the HTML markup ¤  Which events control the execution of a script (e.g., events of loading a document or click on a button) ¤  The HTTP protocol functionalities are exploited for retrieving scripts
  • 16. Standards: DOM The DOM (Document Object Model) is an object oriented model for representing HTML and XML documents
  • 18. JavaScript ¤  JavaScript is the language of the web browser ¤  Good parts ¤  Functions are objects ¤  Dynamic objects (“Want to add another property? Do it!”) ¤  Loose typing ¤  Bad parts ¤  Model based on global variables
  • 19. JavaScript vs. Java ¤  Java and JavaScript share just similarities on the name! ¤  JavaScript is a scripting language ¤  Interpreted ¤  Uses the browser for the input/output procedures ¤  Loose typing ¤  Nothing to be installed (interpreted by the browser, natively) ¤  Java is a programming language ¤  Compiled in bytecode; executed on a virtual machine ¤  Strong typing ¤  Used as a standalone program or as an applet
  • 20. An example: Fibonacci (1) <html>! <head>! !<title>Fibonacci series</title>! !<script language="JavaScript"> !! ...script...! !</script>! </head>! <body>! <button onclick="computeFibonacciSeries()">Compute Fibonacci Series</button>! !<div id="content"></div>! </body>! </html> The results are stored here
  • 21. An example: Fibonacci (2) function computeFibonacciSeries() {! !var contentDiv = document.getElementById("content");! !var header = document.createElement("h3");! !header.appendChild(document.createTextNode("Fibonacci series:"));! !contentDiv.appendChild(header);! ! ! ! !! !var first = 0, second = 1, temp; ! !for(i=1; i<10; i++) { ! temp = first + second; ! contentDiv.appendChild(document.createTextNode(first));! contentDiv.appendChild(document.createElement("br")); ! first = second; ! second = temp; ! !}! };! Retrieve the reference to the div Store the computed number in the content div
  • 23. Grammar: Whitespaces and comments ¤  Whitespace ¤  It can take the form of formatting characters or comments ¤  It is necessary to use whitespace to separate sequences of characters that would be combined into a single token ¤  var that = this;! ¤  Comments ¤  // This is a comment on a line! ¤  /* This is a comment that can be written in multiple lines */!
  • 24. Grammar: Names ¤  A name is a letter optionally followed by one or more letters, digits or underbars ¤  Reserved words: abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with!
  • 25. Grammar: Numbers ¤  JavaScript has a single number type (64-bit floating point, the same as Java double) ¤  No separate integer type (1 and 1.0 are the same) ¤  Exponents: 100 = 1e2 ¤  Negative numbers are formed by using the – prefix operator ¤  Special numbers ¤  NaN is the result of an operation that cannot produce a normal result ¤  Infinity represents the infinity value ¤  The Math object contains a set of methods that act on numbers
  • 26. Grammar: Strings ¤  A string can be wrapped in single or double quotes ¤  The char type is not present (use a string containing just one character!) ¤  The “” is the escape character ¤  The length property is used to compute the string length ¤  “seven”.length = 5 ¤  Strings are immutable, i.e., once they are made, they can never be changed ¤  New strings can be created by concatenating other strings with the + operator
  • 27. Grammar: Statements ¤  Each <script> tag delivers a compilation unit that is compiled and immediately executed ¤  Statements are executed from top to bottom ¤  The sequence of execution can be altered by the conditional statements (if and switch), by the looping statements (while, for and do) and by the disruptive statements (break, return and throw) ¤  A block is a set of statements wrapped in curly braces ¤  Blocks do not create a new scope: variables have to be defined at the top of the function, not in blocks
  • 28. Grammar: if statement ¤  if (expression) then {block} else {block}! ¤  False values ¤  False, null, undefined, ‘’, 0, NaN ¤  True values ¤  All the other values
  • 29. Grammar: for statement ¤  for (initialization; condition; increment) {block}! ¤  If the condition is false, the loop breaks ¤  Otherwise, the block is executed, the increment executes, and the loop repeats with the condition ¤  for (variable in object) {block}! ¤  Enumeration of the property names of an object ¤  On each iteration, the current property name is assigned to the variable
  • 30. Grammar: try, catch, throw (1) ¤  The try statement executes a block and catches any exceptions that were thrown by the block ¤  The catch clause defines a new variable that will receive the exception object ¤  The throw statement raises an exception ¤  It throw is in the try block, the control goes to catch! ¤  In throw is not in the try block, the function is abandoned, and the control goes to the catch clause of the try in the calling function
  • 31. Grammar: try, catch, throw (2) Example of throw var add = function(a,b) {! if (typeof a !== ‘number’ || typeof b !== ‘number’) {! throw {! name: ‘TypeError’,! message: ‘add function needs numbers’! };! }! return a + b;! }!
  • 32. Grammar: try, catch, throw (3) Example of try/catch var try_it = function() {! !try {! ! !add(“seven”);! !}! !catch (e) {! ! !document.writeln(e.name + “: “ + e.message);! !}! }!
  • 33. Grammar: return, break! ¤  The return statement causes the early return from a function ¤  A return value can be specified ¤  If the return value is not specified, the return value will be undefined ¤  The break statement causes the exit from a loop statement or a switch statement
  • 34. Grammar: other statements ¤  An expression statement can: ¤  Assign values to one or more variables or members ¤  Invoke a method ¤  Delete a property from an object ¤  The = operator is used for assignment ¤  The === / == operator is the equality operator ¤  ===: equality for both the value and the type ¤  ==: equality for the value ¤  The += operator can add or concatenate
  • 35. Operators Operators Meaning . [] ()! Refinement and invocation delete new typeof + - !! Unary operators * / %! Multiplication, division, modulo + -! Addition/concatenation, subtraction >= <= > <! Inequality === !== == !=! Equality &&! Logical AND ||! Logical OR ?:! Ternary
  • 36. Prefix operators ¤  Typeof ¤  ‘number’, ‘string’, ‘boolean’, ‘undefined’, ‘function’, and ‘object’ Operators Meaning !! Logical not +! Add or concatenate -! Negate
  • 37. Loose typing vs. Strong typing ¤  Most programming languages demand strong typing ¤  Pro: you can detect errors at compile time ¤  Cons: casting between different types ¤  JavaScript is a loosely typed programming language ¤  Pro: no casting between different types ¤  Cons: you cannot understand whether there are errors until you execute the code
  • 38. Javascript: part 2 Eleonora Ciceri Ph.D. student – Politecnico di Milano eleonora.ciceri@polimi.it
  • 40. Java: what is an object? ¤  A class defines the data type and allows the creation of objects ¤  The object characteristics reflect the ones required by the class definition maxSpeed doors color myCar = new Car();! myCar adheres to the schema defined when the class was declared There is not the possibility to extend the object by adding and/or removing attributes/methods
  • 41. JavaScript: what is an object? ¤  Well, everything is an object ¤  “Objects are class-free containers used for collecting and organizing data” ¤  Moreover, you can define your own objects Simple data types (Either used as primitive data or objects) ü  Booleans ü  Numbers ü  Strings Complex data types ü  Dates ü  Arrays ü  Functions
  • 42. How to build JavaScript objects ¤  Definition: an object is a special kind of data with: ¤  Properties: the values associated with an object ¤  Methods: the actions that can be performed on an object ¤  How to access to an object? Property objectName.propertyName! Method objectName.methodName() car.color! car.run()!
  • 43. Creating JavaScript objects: Create a direct instance ¤  It is possible to create an object on the fly, by adding properties to it ¤  Translated: 1.  Create an empty object 2.  Add the firstName property with value John! 3.  … person = new Object();! person.firstName = “John”;! person.lastName = “Doe”;! person.age = 50;! person.eyeColor = “blue”;!
  • 44. Creating JavaScript objects: Create a direct instance ¤  Every time a property is added to the definition, the object schema is expanded to contain the new property ¤  This suggests that JavaScript objects are flexible and not tied to a given schema ¤  JavaScript objects are class-free person.firstName! person.firstName! person.lastName! person.firstName! person.lastName! person.age!
  • 45. Creating JavaScript objects: Create an object literal ¤  An object literal is a pair of curly braces surrounding zero or more name/value pairs ¤  This equals to add properties one at a time to the object var empty_object = {};! var employee = {! “first-name”: “Jerome”,! “last-name”: “Howard”! };!
  • 46. Creating JavaScript objects: Use an object constructor ¤  Here comes the this reference: ¤  We are going to handle more than one person at a time ¤  Which person we are dealing must be clear ¤  this indicates the instance of object at hand function person(firstName, lastName, age, eyeColor) {! this.firstName = firstName;! this.lastName = lastName;! this.age = age;! this.eyeColor = color;! }!
  • 47. Creating JavaScript objects: Use an object constructor ¤  Once you have a new constructor, you can create an object instance: ¤  The constructor automatically fills the properties by using the values that are passed as parameters var myFather = new person(“John”,”Doe”,50,”blue”);!
  • 48. Add properties anywhere, anytime ¤  When an object has been created, you can decide to add new properties at each point of your script ¤  The object keeps updating itself every time an expansion is required object = new Object();! object.myProperty = “MyProperty”;! [do some stuff]! [do some other stuff]! object.mySecondProperty = “MySecondProperty”;! [do more and more stuff]! object.myThirdProperty = “MyThirdProperty”;!
  • 49. Adding methods to JavaScript objects ¤  Methods are just functions attached to objects ¤  Their definition is done inside the object constructor function function person(firstName, lastName, age, eyeColor){! this.firstName = firstName;! this.lastName = lastName;! this.age = age;! this.eyeColor = eyeColor;! this.changeName = changeName;! function changeName(name) {! this.lastName = name;! }! } !
  • 50. Adding methods to JavaScript objects ¤  This just expands the object, as in the case of the properties ¤  The only difference is that methods are functions, so they manipulate data rather than adding new fields ¤  The function can be then called on the object: ¤  myMother.changeName(“Doe”);! person.firstName! person.lastName! person.age! person.changeName()!
  • 51. Object prototype ¤  Every object is linked to a prototype object from which it can inherit properties ¤  Object are linked to Object.prototype, an object that comes standard with JavaScript ¤  The prototype link has no effect on updating ¤  Changes to an object do not affect the object’s prototype ¤  The prototype is dynamic ¤  If we add a new property to the prototype, it will be visible in all the objects that are based on the prototype
  • 52. Object prototype Not here? Retry with its prototype Not here? Retry with its prototype … Returns property Returns undefined!
  • 53. Reading properties: Inspection ¤  We have seen that this retrieves a property: person.firstName! ¤  This retrieves exactly the same property: person[firstName]! ¤  And this too: person[“firstName”]!
  • 54. Reading properties: Inspection ¤  So, how to select the appropriate access method? ¤  The quotes are required for names that : ¤  Correspond to reserved words ¤  Contain special characters (e.g., -, _, whitespaces) ¤  The dot notation usage depends on quotes: ¤  Can be used if the property name does not require quotes (but this is not strictly necessary) ¤  Cannot be used if the property name require quotes; in this case, go for []
  • 55. Reading properties: Inspection ¤  We have seen that this returns a property: person[“firstName”]! ¤  We have also seen that strings can be declared either using single quotes or using double quotes ¤  Since the property name is in this case a string, the following returns exactly the same property: person[‘firstName’]!
  • 56. Reading properties: Inspection ¤  The typeof operator reads the property type ¤  The values can correspond either to data or to functions ¤  typeof person.toString returns ‘function’ ¤  The hasOwnProperty method returns true if the object has that particular property, without looking at the prototype chain
  • 57. Reading properties: Enumeration ¤  Now the iteration over the object properties should be clear… ¤  Which is the output? var person = {firstName:”John”, lastName:”Doe”};! text = “”;! for (property in person) {! text = text + person[property] + “ “;! }!
  • 58. Reading properties: Enumeration ¤  Now the iteration over the object properties should be clear… ¤  Which is the output? ¤  N.B. The order in which the properties are printed is not guaranteed var person = {firstName:”John”, lastName:”Doe”};! text = “”;! for (property in person) {! text = text + person[property] + “ “;! }! John Doe
  • 59. Reading non-existing properties ¤  What if we try to access to person.numChildren? ¤  Remember? We didn’t define its value ¤  Yet another difference between Java and JavaScript: ¤  Java: not working ¤  JavaScript: if the value is not defined, and the undefined value is defined: ¤  Since this is not so nice to be handled, we can modify to: ¤  var middle = employee[“middle-name”] || “(none)”;! person.numChildren returns undefined !
  • 60. Reading undefined! ¤  Be really careful: don’t try to access to the internals of undefined! ¤  Attempting to retrieve values from undefined will throw a TypeError exception undefined TypeError
  • 61. Update object properties ¤  If the property already exists, it is replaced: ¤  person[‘firstName’] = ‘John’;! ¤  If the object does not already have that property name, the object is augmented: ¤  person[‘nickname’] = ‘Curly’;!
  • 62. Delete object property ¤  The delete operator removes a property from an object ¤  delete person.nickname! ¤  If a property can’t be deleted, the operation returns false! ¤  N.B. Variables cannot be deleted… ¤  var x = 1;! ¤  delete x; // false! ¤  …and neither can be functions: ¤  function x() {}! ¤  delete x; // false!
  • 63. Object references ¤  Objects are passed around by reference (never copied!) person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘John’ person
  • 64. Object references ¤  Objects are passed around by reference (never copied!) person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘John’ person x
  • 65. Object references ¤  Objects are passed around by reference (never copied!) person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘Sam’ person x
  • 66. Object references ¤  Objects are passed around by reference (never copied!) ! ¤  name is ‘Sam’ because x and person are references to the same object person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘Sam’ person x name
  • 67. Object references ¤  var a={}, b={}, c={}! ¤  a, b and c refer to different empty objects ¤  var a = b = c = {}! ¤  a, b and c all refer to the same empty object a b c a b c
  • 68. Global objects ¤  All the top-level variables of all compilation units are tossed together in a common namespace called the global object ¤  Needed because: global variables can hold all of the assets of an application ¤  Disadvantage: they increase the possibility that different applications interact badly together, “stealing” other applications’ variables
  • 69. Global objects ¤  Solution: usage of a single global variable! var MYAPP = {};! MYAPP.employee = {! “first-name”: “John”,! “last-name”: “Doe”! };! ¤  Advantages ¤  Reduce the chance of bad interactions with other applications, widgets or libraries ¤  Enhanced readability of the program
  • 71. Functions ¤  What is a function? ¤  A block of code that encloses a set of statements ¤  An object ¤  Why do we use functions? ¤  Code reuse ¤  Information hiding ¤  Composition
  • 72. Functions ¤  Since functions are objects, they can be: ¤  Stored in variables, objects and arrays ¤  Passed as arguments to functions ¤  Returned as the result of a function ¤  Functions can have properties and methods
  • 73. Functions that return a function ¤  A function can return another function as return value ¤  There is a really important difference: ¤  Assigning a variable to a function (without the parenthesis) copies the reference to the function ¤  Putting the parenthesis at the end of a function name calls the function and returns the function return value
  • 74. Functions that return a function function a() {! alert('A');! }! //alerts 'A', returns undefined! ! function b() {! alert('B');! return a;! }! //alerts 'B', returns function a! ! function c() {! alert('C');! return a();! }! //alerts 'C', alerts 'A', returns undefined! ! alert("Function 'a' returns " + a());! alert("Function 'b' returns " + b());! alert("Function 'c' returns " + c());!
  • 75. Function closure ¤  Functions can be defined inside other functions ¤  An inner function can access to the parameters and variables of the functions it is nested within ¤  The function object created by a function literal contains a link to that outer context ¤  This is called closure
  • 77. Function closure This function can see these variables Closure
  • 79. Closure ¤  There are cases when an inner function has a longer lifetime than its outsider function ¤  The closure is adopted to implement private variables, getters and setters var fade = function (node) {! var level = 1;! var step = function () {! var hex = level.toString(16);! node.style.backgroundColor = ‘#FFFF’ + hex + hex;! if (level < 15) {! level += 1;! setTimeout(step,100);! }! };! setTimeout(step,100);! };! This function can see level, and operates on itAll these variables live until the function needs them; when the function terminates, they are deleted
  • 80. Function literals var add = function sum(a,b) {! return a + b;! };! Reserved word Function’s name (optional) •  Used to call the function recursively •  If not defined, the function is said to be anonymous Function’s parameters Parameters are variables in the function, initialized with the provided value Function’s statements The body of the function executed when the function is invoked
  • 81. Scope ¤  A scope defines the visibility and the lifetime of variables and parameters ¤  JavaScript does not have block scope ¤  All the variables defined in a block are not visible from outside the block ¤  JavaScript has function scope ¤  Parameters and variables defined in a function are not visible outside the function ¤  A variable defined in a function is visible in the function ¤  Inner function can access parameter and variables of the function they are defined within
  • 82. Function invocation ¤  Invoking a function suspends the current function ¤  The control is passed to the new function ¤  Parameters are passed too ¤  Passed parameters ¤  The ones specified by the user ¤  this!
  • 83. Function invocation ¤  A function may be called with any number of arguments function go(a,b) {! alert('A=’+ a +’; B=’+ b);! }! go(1)! go(1,2)! go(1,2,3)! a=1,b undefined a=1,b=2 a=1,b=2, third parameter is not listed
  • 84. Function invocation: Method Invocation Pattern ¤  Functions can be stored as properties of an object ¤  The parameter this is bound to that object ¤  It is used to refer to the object when a modification is needed var myObject = {! value: 0,! increment: function (inc) {! this.value += typeof inc === ‘number’ ? inc : 1;! }! };!
  • 85. Function invocation: Function Invocation Pattern ¤  There can be functions which are not properties of an object ¤  These functions are bounded to the global object ¤  A method cannot use an inner function to help if do its work, (the inner function does not share a reference to this) myObject.double = function() {! var that = this;! var helper = function (){! that.value = add(that.value, that.value);! };! helper();! };! To let this function access to this, we have to store a reference to it in the that variable, which is visible in the inner function
  • 86. Function invocation: Constructor Invocation Pattern ¤  The functions invoked with the new prefix are called constructors ¤  When the function is called, a new object is created ¤  The object contains a link to the value of the function’s prototype member var Quo = function(string) {! this.status = string;! };! Quo.prototype.get_status = function() {! return this.status;! };! var myQuo = new Quo(“confused”);! Constructor: this creates an object with a status property Give all instances of Quo a public method called get_status Create a new instance of Quo
  • 87. Function invocation: Apply Invocation Pattern ¤  The apply method allows to ¤  Choose the value of this! ¤  Build an array of arguments to use to invoke a function var array = {3,4};! var sum = add.apply(null, array);! /**********************************/! var Quo = function (string) {! this.status = string;! }! var statusObject = {! status: ‘A-OK’;! };! Status = Quo.prototype.get_status.apply(statusObject);! Create an array of two numbers and add them Create an object with a status member Constructor (see previous slide) The variable Status is equal to ‘A-OK’!
  • 88. Function arguments! ¤  The arguments array is available to functions when they are invoked ¤  The arguments array give access to all the values supplied with the invocation ¤  It includes additional ones, not assigned to parameters ¤  It allows the definition of functions with an unspecified number of parameters ¤  Notice that arguments is not a proper array ¤  It has the length property ¤  It lacks all the other methods
  • 89. Function return! ¤  The last } in a function returns the control to the part of the program that invoked the function ¤  The return statement can be used to cause a function to return early ¤  A function always returns a value ¤  Undefined: if the return value is not specified, then undefined is returned ¤  This: if the function was invoked with the new prefix, then the return value this is returned
  • 90. Callbacks ¤  A callback is useful to deal with discontinuous events ¤  A function can be passed to another function as parameter ¤  This function will be invoked asynchronously ¤  Example: AJAX requests request = prepare_the_request();! ! send_request_asynchronously(! request, ! function (response) {! display(response);! }! };!
  • 92. What is an array? ¤  An array is a linear allocation of memory in which elements are accessed by integers that are used to compute offsets
  • 93. What is an array in JavaScript? ¤  Problem: although they are very efficient and useful, JavaScript does not have them L ¤  Solution: JavaScript provides an object that has some array-like features ¤  Array subscripts are converted into strings and are used as indexes ¤  Elements in an array can contain any mixture of values
  • 94. Example: array misc! var misc = [! ‘string’, 98.6, true, false, null, undefined, [‘nested’, ‘array’], {object: true}, NaN, Infinity! ];! ¤  If misc.length is invoked, the result 10 is retrieved ‘string’ 98.6 true false null undefined ‘nested’ {object:true} NaN Infinity ‘array’ 1 2 3 4 5 6 7 8 9 10
  • 95. Array literal vs. object literal (1) var numbers = [! ‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’, ‘seven’, ‘eigth’, ‘nine’! ];! var numbers_object = {! ‘0’: ‘zero’, ‘1’: ‘one’, ‘2’: ‘two’, ‘3’: ‘three’, ‘4’: ‘four’, ‘5’: ‘five’, ‘6’: ‘six’, ‘7’: ‘seven’, ‘8’: ‘eight’, ‘9’: ‘nine’! }! Both numbers and numbers_object are objects with 10 properties, having the same names and values •  numbers inherits from Array.prototype (length property, other array methods) •  numbers_object inherits from Object.prototype (no length property)
  • 96. Array length ¤  The length property is an upper bound ¤  When a subscript greater than the array length is used, this increases the array length ¤  Thus, the length is the largest integer property name in the array plus one, not the number of properties in the array! ¤  Length can be set explicitly ¤  If the length is greater than the number of properties, this does not allocate more space for the array ¤  If the length is smaller than the number of properties, this causes properties to be deleted
  • 97. Modify arrays ¤  The delete operator can be used to remove elements from arrays ¤  This leaves a hole in the array, since the element on the right holds its original name ¤  delete numbers[2];! ¤  The splice method deletes some number of elements and replace them with other elements (specified from the third parameter) ¤  numbers.splice(2,1);! The position from which elements are deleted How many elements are deleted
  • 98. Access to arrays ¤  The for…in operator can be used to iterate over arrays ¤  This works in the same way as accessing to object properties ¤  Problems ¤  No guarantee about the order of the properties ¤  Some browser drags unexpected properties from the prototype chain ¤  Arrays in JavaScript are not initialized (thus missing elements have an undefined value)
  • 99. Matrices ¤  JavaScript does not have multi-dimensional arrays (but one can define arrays of array) …
  • 101. typeof! ¤  The typeof operator returns a string that identifies the type of its operand ¤  Problem: typeof null returns ‘object’ instead of ‘null’ ¤  typeof cannot distinguish between null and objects, but you can because null is false and all objects are true ¤  A better test for null is: myValue === null?
  • 102. Equality ¤  Equality operators are === and !== ¤  If two objects are of the same type and with the same value, then the operator === returns true ¤  The operator == tries to compare objects of different types ‘’ == ‘0’! False 0 == ‘’! True 0 == ‘0’! True false == ‘false’! False false == 0! True false == undefined! False false == null! False null == undefined! True
  • 105. References ¤  Wikipedia, “Scripting language” ¤  JavaScript: The Good Parts, Douglas Crockford, O’Reilly ¤  http://javascript.crockford.com/ (videos!) ¤  W3C Javascript Tutorial: http://www.w3schools.com/js/ default.asp ¤  HTML.it Javascript: http://javascript.html.it/