SlideShare a Scribd company logo
1 of 77
Introduction to JavaScript
Dr. Andres Baravalle
Lecture plan
• Starting to program
• Introduction to JavaScript
• Lexical structure
• Variables and data types
• Expressions
• Operators
• Objects and functions
STARTING TO PROGRAM
Starting to program
• The following slides should appear familiar as
you have done some programming before
– If you are familiar with basic programming concepts
such as variables, arrays, conditional statements and
loops, you should be able to understand and use
JavaScript quite rapidly.
INTRODUCTION TO
JAVASCRIPT
WWW technologies
• Since the advent of the World Wide Web (WWW) much of the focus
in computing has been on technologies that work with, or on, the
World Wide Web. This includes W3C technologies
as HTML, CSS and XML (that work on the web) but also
programming languages as Java, Python, Ruby - the allow to build
applications that rely on - or use - the World Wide Web.
• These technologies can be grouped (by function) into three main
layers:
– Languages for structuring content (such as HTML 5 or XML)
– Languages to manage the presentation layer of information (such as CSS)
– Languages to manage the interaction of the user with the structure and with the
presentation (such as JavaScript or PHP).
WWW technologies and layers
• At this point, it would be useful to summarise the more important
WWW technologies, and in which layers they operate.
• Please note that any technology can be used in different ways; we
are now focusing on the more common uses of the technologies.
• Some of the technologies focus on just one of the layers that we
have identified:
– XHTML and HTML5 are mark-up languages used to structure the content of
web pages
– XML (Extensible Mark-up Language) is a language that allows to structure
arbitrary content. Historically, XML was defined only after HTML, trying to
overcome some of its limitations
– CSS is a style language used to add presentation information, of XML dialects
and HTML.
WWW technologies and layers
(2)
• A number of languages implement features
of all three layers:
– Flash is a technology from Adobe to create animations,
interactive movies and rich Web applications (Web applications
that have features and functionalities similar to the ones of
desktop applications).
– Java is a technology from Oracle (formerly Sun) that is used in
different fields of computing. It can be used for Web
development, on both the client side and server side. Java
programs embedded in web pages on the client side are
called Java applets.
– PHP is a server-side scripting language used for web
development.
– JavaScript (more later!)
JavaScript
• JavaScript is a language that is largely
used in the Word Wide Web to add client-
side interactivity to web pages
– JavaScript has been first included in
Netscape 2, in 1995!
ECMAScript
• ECMAScript is a scripting language standardised by ECMA in June
1997, based on the JavaScript specifications from Netscape but
with a vendor-neutral name.
• While the original ECMAScript was based on JavaScript, now it’s
the other way around and JavaScript is based on ECMAScript:
– The latest version of ECAMAScript is ECMAScript 6 – released in June
2015
– The current version of JavaScript is 1.8.5, compliant with ECMAScript 5
– Other ECAMAScript-based languages are ActionScript (used in Adobe
Flash) & Jscript (the Microsoft implementation, used in Microsoft
products)
Client side JavaScript
• Client side JavaScript is simply JavaScript
that runs on the client
• In this module, you’ll be using client side
JavaScript only (but there’s also server
side JavaScript – although is not very
used)
Client side JavaScript (2)
• These are some client side JavaScript
methods – to get you started:
– document.write(), to write in a document
– alert(), to open a pop-up window
– prompt(), to capture user input
– confirm(), to get a yes/no answer from the
user
Inserting JavaScript
• There are three common ways of inserting
JavaScript code in a web page:
– Inside an HTML tag script
– In an external file
– As a value of some HTML attributes
JavaScript in a tag script
• Inside an HTML tag script:
<script type="text/javascript">
alert("JavaScript is working in your
browser");
</script>
JavaScript in an external file
• Inside an external .js file, linked to the
HTML page:
<script type="text/javascript"
src="path/to/file.js"> </script>
• The external .js file will include just the
JavaScript code, no HTML
JavaScript as a value of some
HTML attributes
• <a href="javascript:alert('JavaScript is
working in your browser');">link</a>
Hello Word!
• You are now ready to write your first Hello
World file – and then we will go through
JavaScript syntax
Hello Word! (2)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
</head>
<body>
<script type="text/javascript">
document.write("<p>Hello World</p>");
</script>
</body>
</html>
Before you start
• You’ll need a suitable editor – Aptana
Studio, Adobe Dreamweaver, Notepad++
are all ok
• You’ll need Firebug to debug your scripts
– download an install it on Firefox
• You’ll need a JavaScript reference; please
download the “Open JavaScript Guide”
from from sourceforge:
http://sourceforge.net/projects/javascriptguide/
Activity #1
• You have seen three different approaches
to include JavaScript code in a web page
• Create 2 simple hello world pages – one
like the one demonstrated a few slides
before, one using an external file.
LEXICAL STRUCTURE
JavaScript: lexical structure
• In the next slides we are going to
understand the lexical structure of
JavaScript (that is, the meaning of its
terms)
• Learning the lexical structure means
understanding the elements that are used
when creating scripts
JavaScript: semicolons
• A JavaScript program is quite simply a
sequence of instructions made up of
symbols (such as keywords, characters
with special meaning, numbers and text
chunks) to which the language associates
a special meaning
• Simple statements in JavaScript are
typically followed by a semicolon (;):
var x = 1; var y = 2;
JavaScript: semicolons (2)
• You may omit the semicolon if each of the
statements is a placed on a separate line:
var x = 1
var y = 2
– You should follow every statement by a semicolon
and a new line
– Readability of the code is improved by using
semicolons after every statement, and it is a
requirement in other development languages
Whitespace
• Whitespace (spaces, tabs and newlines)
can be used freely to format and indent
the code
• If you insert a new line and the chunk of
code that is left in the line appears to be a
complete, valid statement, JavaScript will
insert an implicit semicolon, possibly
altering the meaning of the code.
Whitespace (2)
• Consider this code:
return
true;
• which will be interpreted as:
return;
true;
• The code will return the value undefined (which
is the default value when return is called without
a parameter), instead of the value true.
Case sensitivity
• Computer languages can be case
sensitive or case insensitive (or may be
a combination of both)
• JavaScript is case sensitive, which means
that the name of keywords and other
language identifiers must always be
typed with the correct capitalisation
Comments
• Comments are chunks of text which are
not executed but are placed to ensure that
the code can be read in an easier way
• You should get into the habit of using
comments in abundance, both to make
sure that other developers can understand
your code (unless you explicitly want to
avoid that) and to refresh your own
memory when returning to it
Comments (2)
• JavaScript has two ways of inserting
comments:
// the rest of the line is a comment
/*
This block of text is a comment.
In this way I can comment on multiple
lines at the same time.
*/
Literals
• Programming requires manipulation of
data. In JavaScript, data that appear
directly in a program are called literals.
• For example:
– "Hello world"
– 15
– null
– true
– false
VARIABLES AND DATA TYPES
Data types
• A program normally handles data in some form
or other
• For example, a program created to calculate and
print a credit-card bill would deal with the:
– Amounts that have been charged to the card
– Names of the companies charging the card
– Dates of charges to the card
– Card owner’s name
– Card owner’s address
• All these items can be termed data
Data types (2)
• JavaScript supports a number of different
data types. The main ones are:
– Number
– String
– Boolean
• Other data types include:
– Null & undefined
Declaring variables and storing
values
• This is done by using a statement – like
these:
• x = 0.01; // Just one Number type for
integers and floats
• This statement creates a variable x, of
type Number
– This is called typing, and statements that do
that are called ‘type statements’.
Declaring variables and storing
values (2)
• x = 0.01; // Just one Number type for
integers and floats
• x = "hello world"; // Strings of text in
quotation marks.
• x = true; // Boolean values
• x = null; // Null is a special value that
means "no value”
Declaring variables and storing
values (2)
• The statement gives the variable a value
using the operator ‘=’
– The first time you assign a value to a variable
is typically called initialisation
• Statements – as this one - that declare a
variable’s name and type are also
frequently called declarations
EXPRESSIONS
Expressions
• Programming in any language requires
manipulating data. In some cases, the
data will be just literals (such as text
strings) but quite often more complex
expressions will be used.
• Anything that can be evaluated by the
JavaScript interpreter can be thought of as
an expression, just as literals are any data
that appear directly in a program.
Expressions (2)
• Expressions can use a number of different
operators, or no operators at all
• For example:
x * 2
• Individual expressions can be combined
together with operators to create a compound
expression, whose value is calculated at
runtime:
x + y/4
x - y + 2
OPERATORS
Operators
• Operators are special functions that
operate on one to three values
(operands).
• The most common operators require one
operand (unary operators) or two
operands (binary operators).
– Unary operators require a single operand,
which can be before or after the operator.
– Binary operators require two operands, one
before and one after the operator
Operators (2)
• You have already seen a few operators
that are a part of JavaScript
– The assignment operator (‘=’)
– The operators for the basic math operations
(addition, subtraction, multiplication, division)
• JavaScript includes a good number of
operators, but we are going to focus on
those that will be more useful for your
forthcoming studies
Assignment operators
• Used to assign the value of the right
operand to the left operand:
x = y;
• The right operator can be any type of
expression:
x = x + y;
Assignment operators (2)
• JavaScript includes a number of
shorthand assignment operators:
x+=y;
• is equivalent to:
x = x + y;
• Shorthand assignment operators are
available for the four main arithmetic
operations: +=, -=, /=, *=, plus a number of
others.
Arithmetic operators
• The simplest arithmetic operators are: addition (+),
subtraction (-), multiplication (*), and division (/)
• Other useful arithmetic operators are the unary (with just
one operand) increment (++) and decrement (--)
operators
• For example:
x = 1;
x++; // x is set to 2
y = x++; // y is set to 2 and x is set to 3
z = ++y; // y and z set to 3
Comparison operators
Operator Symbol
Equal ==
Strictly equal ===
Not equal !=
Strictly not equal !==
Greater than >
Greater than or equal >=
Less than <
Less than or equal <=
Comparison operators (2)
• Comparison operators are used to compare the
operands and return a Boolean value (True or False)
• Remember that there is an operator for assignment (=)
and an operator to compare if two variables are
equal (==)
• The strictly equal (===) and strictly not equal (!==)
operators compare the type of the variable too – if the
type does not match, the variables are not equal.
Logical operators
• Logical operators are used to connect different
expressions
• The basic operators are and (&&), or (||), not (!)
• Look at the examples:
x == 1 && y ==2 // True if x equals 1 and y equals 2
x == 1 || y == 2 // True if x equals 1 or if y equals 2
x != 1 // True if x is not equal to 1
String operators
• JavaScript has an operator (+) to
concatenate strings
• The + operator is also used to add two
numbers
– You can see how the + operator has two
different meanings, one between numbers
and another between strings
Activity #2
• Creare a script asking for the name and
surname of a person when loading the
page (use prompt(), and store name and
surname in 2 different variables)
• Wellcome the user with a message
(alert()) "Wellcome name surname".
Activity #3: writing stylesheets!
• Ask the user (prompt()) whether he would
like a normal, big or low size for fonts in
the screen
• Use JavaScript to write an internal
stylesheet reflecting the user’s
preferences
– Customise the tags h1, h2, body and p
– Demonstrate how the user choice will change
the style of content in the page
Precedence
• There are situations in which different operators
are used, one after the other
• If an expression has more than one operator
there are multiple ways in which the expression
can be evaluated
• The expression:
4 / 2 + 2 * 3
• could evaluate to 12 or to 8 depending on which
operator is applied first.
Precedence (2)
• To prevent this type of ambiguity, operators are
each given a precedence and an associativity.
• Precedence controls the order in which
operators are evaluated; a higher precedence
operator, a larger precedence value, is
evaluated first
• For example, multiplication and division have a
higher precedence than addition and
subtraction.
Associativity
• Associativity describes how to process
them (right-to-left or left-to-right).
• Associativity for arithmetic operators is
left-to-right, and for comparison operators
is right-to-left.
Associativity (2)
• Now, if we have a look at this code:
var x = 1;
var y = 2;
var z = 3;
y += x *= z;
• The value of x, y and z after the last operation depends
on whether x *= z or
y += x is executed first.
• As we have two assignment operators, and their
associativity is right-to-left, we know what will be the
order in which they will be analysed.
STATEMENTS
Statements
• Statements are instructions that tell the
interpreter to perform an action.
• You have already seen some examples of
statements in:
x = 1;
counter --;
Conditional statements: if
• The if statement allows you to test an
expression and then make a branch in the
script’s flow of control
• You can nest if statements, obtaining
multi-way branches
Conditional statements: if (2)
if (number == 1) {
// first branch:
// applicable if number is '1'
} else {
if (number == 2) {
// second branch:
// applicable if number is '2'
} else {
// optional 'catch all' branch
// statements applicable if number is not '1' or '2’
}
}
Activity #4: if… else…
• Ask the user whether s/he would want to
receive the mailing list of the website
(confirm()).
• If the users accepts, ask for the email
address (prompt()) and inform (alert()) the
user he has been registered
• Otherwise, thanks the user anyway
(alert())
Conditional statements: switch
• If all the branches depend on the same
expression it is more efficient and clearer
to use a switch statement
Conditional statements: switch
(2)
switch(number) {
case 1:
// statements applicable if number is '1’
break;
case 2:
// statements applicable if number is '2’
break;
default:
// optional 'catch all' branch
break;
}
Activity #5: using switch
• Refactor activity #4, implementing it again
with switch
Loop statements: for
• The for statement is used to perform a sequence
of one or more instructions a number of times
• The general form of the for loop is:
for ( [initialisation]; [test]; [increment] ) {
[statement]
}
• The loop typically initialises a counter which is
then tested against a terminating condition.
Loop statements: while
• The general form of the while loop is:
while ( [test];) {
[statement]
}
Debugging JavaScript
• JavaScript code can be complex, and so it
is important that one of the skills you
acquire during this course is to be able to
identify bugs in the code (this is called
debugging).
Activity #6: debugging
JavaScript
• Try to inspect the following code.
<script type="text/javascript " >
var hello_world = "Hello World;
var text_to_alert = "";
for (var c=1; c<=5; c++) {
text_to_alert += hello_word + ": " + c + " time.n";
}
alert(text_to_alert);
</script>
Activity #6: debugging
JavaScript (2)
• There are two errors in the code (and a
bonus error!); can you see them?
– If you can see the errors – well done! It
means that you are getting familiar with
JavaScript syntax.
• If you can’t see the errors, don’t worry.
Open Firefox and install Firebug, if you
haven’t done it yet.
– Use the Firebug console and tools to identify
the errors.
OBJECTS AND FUNCTIONS
Objects
• Objects are a collection of properties,
each of which has a name and a value
• A property of an object is simply an
additional piece of information held in the
object about the object.
Objects (2)
• Objects are typically used when you
need to structure information
• To access the value of a property, you
have to use a ‘dot’ notation, as we did
in our Hello Word example:
greeting.text = "Hello World";
Functions
• A function is a discrete set of instructions
that carry out some task
• Functions are used to group tasks and to
re-use code
– A function used inside a class is called
method
– We will see later what a class is and how to
use them
Functions (2)
• This is a function stub in JavaScript:
function nameOfTheFunction([parameter_1], [parameter_2],
[parameter_3]) {
// you can use parameter_1, parameter_2, parameter_3 in your
statements
// parameter_1, parameter_2, parameter_3 are local variables,
valid
// only inside the function
[statements]
}
Functions (3)
• This is how to invoke (or ‘call’) the function
in the previous slide:
nameOfTheFunction([parameter_a], [parameter_b],
[parameter_c]);
• The value of parameter_a will be passed
to parameter_1, the value of parameter_b
will be passed to parameter_2 and the
value of parameter_c will be passed to
parameter_3.
Local and global variables
• parameter_a, parameter_b, parameter_c
are said to be global variables, while
parameter_1, parameter_2, parameter_3
are called local variables, valid only inside
the function.
Local and global variables
(example)
function addNumber (number1, number2) {
var number3 = number1 + number2;
// the next line returns the value of total back
// to the global context
// otherwise it would not be available any
more
return number3;
}
var number3 = addNumber(3,5);
Variable scope
• The scope of a variable is the region of
code where it is defined and may be used.
– A ‘global’ variable has global scope: it can be
accessed anywhere in a script.
– Other variables such as those declared within
a function are ‘local’ variables and may only
be accessed within the function.
– Local variable names take precedence over
those with greater scope.

More Related Content

What's hot

What's hot (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Java script
Java scriptJava script
Java script
 
Css Ppt
Css PptCss Ppt
Css Ppt
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to html
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Complete Lecture on Css presentation
Complete Lecture on Css presentation Complete Lecture on Css presentation
Complete Lecture on Css presentation
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Javascript
JavascriptJavascript
Javascript
 
Html presentation
Html presentationHtml presentation
Html presentation
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Html ppt
Html pptHtml ppt
Html ppt
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 

Viewers also liked

Viewers also liked (20)

JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Javascript evolution
Javascript evolutionJavascript evolution
Javascript evolution
 
D3
D3D3
D3
 
Web Technology - PHP Arrays
Web Technology - PHP ArraysWeb Technology - PHP Arrays
Web Technology - PHP Arrays
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Designing and prototyping
Designing and prototypingDesigning and prototyping
Designing and prototyping
 
Accessibility introduction
Accessibility introductionAccessibility introduction
Accessibility introduction
 
Social, professional, ethical and legal issues
Social, professional, ethical and legal issuesSocial, professional, ethical and legal issues
Social, professional, ethical and legal issues
 
Other metrics
Other metricsOther metrics
Other metrics
 
Background on Usability Engineering
Background on Usability EngineeringBackground on Usability Engineering
Background on Usability Engineering
 
Issue-based metrics
Issue-based metricsIssue-based metrics
Issue-based metrics
 
Interfaces
InterfacesInterfaces
Interfaces
 
Usability evaluations (part 2)
Usability evaluations (part 2) Usability evaluations (part 2)
Usability evaluations (part 2)
 

Similar to Introduction to JavaScript

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
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptxAlkanthiSomesh
 
java tutorial for beginners learning.ppt
java tutorial for beginners learning.pptjava tutorial for beginners learning.ppt
java tutorial for beginners learning.pptusha852
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxrish15r890
 
javascriptPresentation.pdf
javascriptPresentation.pdfjavascriptPresentation.pdf
javascriptPresentation.pdfwildcat9335
 
WT Module-3.pptx
WT Module-3.pptxWT Module-3.pptx
WT Module-3.pptxRamyaH11
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)SANTOSH RATH
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMegha V
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
Swift programming language
Swift programming languageSwift programming language
Swift programming languageNijo Job
 
Chapter-introduction about java programming
Chapter-introduction about java programmingChapter-introduction about java programming
Chapter-introduction about java programmingDrRajeshkumarPPatel
 

Similar to Introduction to JavaScript (20)

WTA-MODULE-4.pptx
WTA-MODULE-4.pptxWTA-MODULE-4.pptx
WTA-MODULE-4.pptx
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
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
 
Java script
Java scriptJava script
Java script
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
java tutorial for beginners learning.ppt
java tutorial for beginners learning.pptjava tutorial for beginners learning.ppt
java tutorial for beginners learning.ppt
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptx
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 
javascriptPresentation.pdf
javascriptPresentation.pdfjavascriptPresentation.pdf
javascriptPresentation.pdf
 
WT Module-3.pptx
WT Module-3.pptxWT Module-3.pptx
WT Module-3.pptx
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Swift programming language
Swift programming languageSwift programming language
Swift programming language
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
Chapter-introduction about java programming
Chapter-introduction about java programmingChapter-introduction about java programming
Chapter-introduction about java programming
 

More from Andres Baravalle

Dark web markets: from the silk road to alphabay, trends and developments
Dark web markets: from the silk road to alphabay, trends and developmentsDark web markets: from the silk road to alphabay, trends and developments
Dark web markets: from the silk road to alphabay, trends and developmentsAndres Baravalle
 
Design rules and usability requirements
Design rules and usability requirementsDesign rules and usability requirements
Design rules and usability requirementsAndres Baravalle
 
Usability evaluation methods (part 2) and performance metrics
Usability evaluation methods (part 2) and performance metricsUsability evaluation methods (part 2) and performance metrics
Usability evaluation methods (part 2) and performance metricsAndres Baravalle
 
Planning and usability evaluation methods
Planning and usability evaluation methodsPlanning and usability evaluation methods
Planning and usability evaluation methodsAndres Baravalle
 
Measuring the user experience
Measuring the user experienceMeasuring the user experience
Measuring the user experienceAndres Baravalle
 
SPEL (Social, professional, ethical and legal) issues in Usability
SPEL (Social, professional, ethical and legal) issues in UsabilitySPEL (Social, professional, ethical and legal) issues in Usability
SPEL (Social, professional, ethical and legal) issues in UsabilityAndres Baravalle
 
Accessibility: introduction
Accessibility: introduction  Accessibility: introduction
Accessibility: introduction Andres Baravalle
 
Usability evaluations (part 3)
Usability evaluations (part 3) Usability evaluations (part 3)
Usability evaluations (part 3) Andres Baravalle
 
Data collection and analysis
Data collection and analysisData collection and analysis
Data collection and analysisAndres Baravalle
 
Interaction design and cognitive aspects
Interaction design and cognitive aspects Interaction design and cognitive aspects
Interaction design and cognitive aspects Andres Baravalle
 
Usability: introduction (Week 1)
Usability: introduction (Week 1)Usability: introduction (Week 1)
Usability: introduction (Week 1)Andres Baravalle
 

More from Andres Baravalle (16)

Dark web markets: from the silk road to alphabay, trends and developments
Dark web markets: from the silk road to alphabay, trends and developmentsDark web markets: from the silk road to alphabay, trends and developments
Dark web markets: from the silk road to alphabay, trends and developments
 
Don't make me think
Don't make me thinkDon't make me think
Don't make me think
 
Design rules and usability requirements
Design rules and usability requirementsDesign rules and usability requirements
Design rules and usability requirements
 
Usability evaluation methods (part 2) and performance metrics
Usability evaluation methods (part 2) and performance metricsUsability evaluation methods (part 2) and performance metrics
Usability evaluation methods (part 2) and performance metrics
 
Planning and usability evaluation methods
Planning and usability evaluation methodsPlanning and usability evaluation methods
Planning and usability evaluation methods
 
Measuring the user experience
Measuring the user experienceMeasuring the user experience
Measuring the user experience
 
Don’t make me think
Don’t make me thinkDon’t make me think
Don’t make me think
 
SPEL (Social, professional, ethical and legal) issues in Usability
SPEL (Social, professional, ethical and legal) issues in UsabilitySPEL (Social, professional, ethical and legal) issues in Usability
SPEL (Social, professional, ethical and legal) issues in Usability
 
Accessibility: introduction
Accessibility: introduction  Accessibility: introduction
Accessibility: introduction
 
Usability evaluations (part 3)
Usability evaluations (part 3) Usability evaluations (part 3)
Usability evaluations (part 3)
 
Data collection and analysis
Data collection and analysisData collection and analysis
Data collection and analysis
 
Interaction design and cognitive aspects
Interaction design and cognitive aspects Interaction design and cognitive aspects
Interaction design and cognitive aspects
 
Designing and prototyping
Designing and prototypingDesigning and prototyping
Designing and prototyping
 
Usability requirements
Usability requirements Usability requirements
Usability requirements
 
Usability: introduction (Week 1)
Usability: introduction (Week 1)Usability: introduction (Week 1)
Usability: introduction (Week 1)
 
Don’t make me think!
Don’t make me think!Don’t make me think!
Don’t make me think!
 

Recently uploaded

General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 

Recently uploaded (20)

General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 

Introduction to JavaScript

  • 2. Lecture plan • Starting to program • Introduction to JavaScript • Lexical structure • Variables and data types • Expressions • Operators • Objects and functions
  • 4. Starting to program • The following slides should appear familiar as you have done some programming before – If you are familiar with basic programming concepts such as variables, arrays, conditional statements and loops, you should be able to understand and use JavaScript quite rapidly.
  • 6. WWW technologies • Since the advent of the World Wide Web (WWW) much of the focus in computing has been on technologies that work with, or on, the World Wide Web. This includes W3C technologies as HTML, CSS and XML (that work on the web) but also programming languages as Java, Python, Ruby - the allow to build applications that rely on - or use - the World Wide Web. • These technologies can be grouped (by function) into three main layers: – Languages for structuring content (such as HTML 5 or XML) – Languages to manage the presentation layer of information (such as CSS) – Languages to manage the interaction of the user with the structure and with the presentation (such as JavaScript or PHP).
  • 7. WWW technologies and layers • At this point, it would be useful to summarise the more important WWW technologies, and in which layers they operate. • Please note that any technology can be used in different ways; we are now focusing on the more common uses of the technologies. • Some of the technologies focus on just one of the layers that we have identified: – XHTML and HTML5 are mark-up languages used to structure the content of web pages – XML (Extensible Mark-up Language) is a language that allows to structure arbitrary content. Historically, XML was defined only after HTML, trying to overcome some of its limitations – CSS is a style language used to add presentation information, of XML dialects and HTML.
  • 8. WWW technologies and layers (2) • A number of languages implement features of all three layers: – Flash is a technology from Adobe to create animations, interactive movies and rich Web applications (Web applications that have features and functionalities similar to the ones of desktop applications). – Java is a technology from Oracle (formerly Sun) that is used in different fields of computing. It can be used for Web development, on both the client side and server side. Java programs embedded in web pages on the client side are called Java applets. – PHP is a server-side scripting language used for web development. – JavaScript (more later!)
  • 9. JavaScript • JavaScript is a language that is largely used in the Word Wide Web to add client- side interactivity to web pages – JavaScript has been first included in Netscape 2, in 1995!
  • 10. ECMAScript • ECMAScript is a scripting language standardised by ECMA in June 1997, based on the JavaScript specifications from Netscape but with a vendor-neutral name. • While the original ECMAScript was based on JavaScript, now it’s the other way around and JavaScript is based on ECMAScript: – The latest version of ECAMAScript is ECMAScript 6 – released in June 2015 – The current version of JavaScript is 1.8.5, compliant with ECMAScript 5 – Other ECAMAScript-based languages are ActionScript (used in Adobe Flash) & Jscript (the Microsoft implementation, used in Microsoft products)
  • 11. Client side JavaScript • Client side JavaScript is simply JavaScript that runs on the client • In this module, you’ll be using client side JavaScript only (but there’s also server side JavaScript – although is not very used)
  • 12. Client side JavaScript (2) • These are some client side JavaScript methods – to get you started: – document.write(), to write in a document – alert(), to open a pop-up window – prompt(), to capture user input – confirm(), to get a yes/no answer from the user
  • 13. Inserting JavaScript • There are three common ways of inserting JavaScript code in a web page: – Inside an HTML tag script – In an external file – As a value of some HTML attributes
  • 14. JavaScript in a tag script • Inside an HTML tag script: <script type="text/javascript"> alert("JavaScript is working in your browser"); </script>
  • 15. JavaScript in an external file • Inside an external .js file, linked to the HTML page: <script type="text/javascript" src="path/to/file.js"> </script> • The external .js file will include just the JavaScript code, no HTML
  • 16. JavaScript as a value of some HTML attributes • <a href="javascript:alert('JavaScript is working in your browser');">link</a>
  • 17. Hello Word! • You are now ready to write your first Hello World file – and then we will go through JavaScript syntax
  • 18. Hello Word! (2) <!doctype html> <html> <head> <meta charset="utf-8"> <title>Hello World</title> </head> <body> <script type="text/javascript"> document.write("<p>Hello World</p>"); </script> </body> </html>
  • 19. Before you start • You’ll need a suitable editor – Aptana Studio, Adobe Dreamweaver, Notepad++ are all ok • You’ll need Firebug to debug your scripts – download an install it on Firefox • You’ll need a JavaScript reference; please download the “Open JavaScript Guide” from from sourceforge: http://sourceforge.net/projects/javascriptguide/
  • 20. Activity #1 • You have seen three different approaches to include JavaScript code in a web page • Create 2 simple hello world pages – one like the one demonstrated a few slides before, one using an external file.
  • 22. JavaScript: lexical structure • In the next slides we are going to understand the lexical structure of JavaScript (that is, the meaning of its terms) • Learning the lexical structure means understanding the elements that are used when creating scripts
  • 23. JavaScript: semicolons • A JavaScript program is quite simply a sequence of instructions made up of symbols (such as keywords, characters with special meaning, numbers and text chunks) to which the language associates a special meaning • Simple statements in JavaScript are typically followed by a semicolon (;): var x = 1; var y = 2;
  • 24. JavaScript: semicolons (2) • You may omit the semicolon if each of the statements is a placed on a separate line: var x = 1 var y = 2 – You should follow every statement by a semicolon and a new line – Readability of the code is improved by using semicolons after every statement, and it is a requirement in other development languages
  • 25. Whitespace • Whitespace (spaces, tabs and newlines) can be used freely to format and indent the code • If you insert a new line and the chunk of code that is left in the line appears to be a complete, valid statement, JavaScript will insert an implicit semicolon, possibly altering the meaning of the code.
  • 26. Whitespace (2) • Consider this code: return true; • which will be interpreted as: return; true; • The code will return the value undefined (which is the default value when return is called without a parameter), instead of the value true.
  • 27. Case sensitivity • Computer languages can be case sensitive or case insensitive (or may be a combination of both) • JavaScript is case sensitive, which means that the name of keywords and other language identifiers must always be typed with the correct capitalisation
  • 28. Comments • Comments are chunks of text which are not executed but are placed to ensure that the code can be read in an easier way • You should get into the habit of using comments in abundance, both to make sure that other developers can understand your code (unless you explicitly want to avoid that) and to refresh your own memory when returning to it
  • 29. Comments (2) • JavaScript has two ways of inserting comments: // the rest of the line is a comment /* This block of text is a comment. In this way I can comment on multiple lines at the same time. */
  • 30. Literals • Programming requires manipulation of data. In JavaScript, data that appear directly in a program are called literals. • For example: – "Hello world" – 15 – null – true – false
  • 32. Data types • A program normally handles data in some form or other • For example, a program created to calculate and print a credit-card bill would deal with the: – Amounts that have been charged to the card – Names of the companies charging the card – Dates of charges to the card – Card owner’s name – Card owner’s address • All these items can be termed data
  • 33. Data types (2) • JavaScript supports a number of different data types. The main ones are: – Number – String – Boolean • Other data types include: – Null & undefined
  • 34. Declaring variables and storing values • This is done by using a statement – like these: • x = 0.01; // Just one Number type for integers and floats • This statement creates a variable x, of type Number – This is called typing, and statements that do that are called ‘type statements’.
  • 35. Declaring variables and storing values (2) • x = 0.01; // Just one Number type for integers and floats • x = "hello world"; // Strings of text in quotation marks. • x = true; // Boolean values • x = null; // Null is a special value that means "no value”
  • 36. Declaring variables and storing values (2) • The statement gives the variable a value using the operator ‘=’ – The first time you assign a value to a variable is typically called initialisation • Statements – as this one - that declare a variable’s name and type are also frequently called declarations
  • 38. Expressions • Programming in any language requires manipulating data. In some cases, the data will be just literals (such as text strings) but quite often more complex expressions will be used. • Anything that can be evaluated by the JavaScript interpreter can be thought of as an expression, just as literals are any data that appear directly in a program.
  • 39. Expressions (2) • Expressions can use a number of different operators, or no operators at all • For example: x * 2 • Individual expressions can be combined together with operators to create a compound expression, whose value is calculated at runtime: x + y/4 x - y + 2
  • 41. Operators • Operators are special functions that operate on one to three values (operands). • The most common operators require one operand (unary operators) or two operands (binary operators). – Unary operators require a single operand, which can be before or after the operator. – Binary operators require two operands, one before and one after the operator
  • 42. Operators (2) • You have already seen a few operators that are a part of JavaScript – The assignment operator (‘=’) – The operators for the basic math operations (addition, subtraction, multiplication, division) • JavaScript includes a good number of operators, but we are going to focus on those that will be more useful for your forthcoming studies
  • 43. Assignment operators • Used to assign the value of the right operand to the left operand: x = y; • The right operator can be any type of expression: x = x + y;
  • 44. Assignment operators (2) • JavaScript includes a number of shorthand assignment operators: x+=y; • is equivalent to: x = x + y; • Shorthand assignment operators are available for the four main arithmetic operations: +=, -=, /=, *=, plus a number of others.
  • 45. Arithmetic operators • The simplest arithmetic operators are: addition (+), subtraction (-), multiplication (*), and division (/) • Other useful arithmetic operators are the unary (with just one operand) increment (++) and decrement (--) operators • For example: x = 1; x++; // x is set to 2 y = x++; // y is set to 2 and x is set to 3 z = ++y; // y and z set to 3
  • 46. Comparison operators Operator Symbol Equal == Strictly equal === Not equal != Strictly not equal !== Greater than > Greater than or equal >= Less than < Less than or equal <=
  • 47. Comparison operators (2) • Comparison operators are used to compare the operands and return a Boolean value (True or False) • Remember that there is an operator for assignment (=) and an operator to compare if two variables are equal (==) • The strictly equal (===) and strictly not equal (!==) operators compare the type of the variable too – if the type does not match, the variables are not equal.
  • 48. Logical operators • Logical operators are used to connect different expressions • The basic operators are and (&&), or (||), not (!) • Look at the examples: x == 1 && y ==2 // True if x equals 1 and y equals 2 x == 1 || y == 2 // True if x equals 1 or if y equals 2 x != 1 // True if x is not equal to 1
  • 49. String operators • JavaScript has an operator (+) to concatenate strings • The + operator is also used to add two numbers – You can see how the + operator has two different meanings, one between numbers and another between strings
  • 50. Activity #2 • Creare a script asking for the name and surname of a person when loading the page (use prompt(), and store name and surname in 2 different variables) • Wellcome the user with a message (alert()) "Wellcome name surname".
  • 51. Activity #3: writing stylesheets! • Ask the user (prompt()) whether he would like a normal, big or low size for fonts in the screen • Use JavaScript to write an internal stylesheet reflecting the user’s preferences – Customise the tags h1, h2, body and p – Demonstrate how the user choice will change the style of content in the page
  • 52. Precedence • There are situations in which different operators are used, one after the other • If an expression has more than one operator there are multiple ways in which the expression can be evaluated • The expression: 4 / 2 + 2 * 3 • could evaluate to 12 or to 8 depending on which operator is applied first.
  • 53. Precedence (2) • To prevent this type of ambiguity, operators are each given a precedence and an associativity. • Precedence controls the order in which operators are evaluated; a higher precedence operator, a larger precedence value, is evaluated first • For example, multiplication and division have a higher precedence than addition and subtraction.
  • 54. Associativity • Associativity describes how to process them (right-to-left or left-to-right). • Associativity for arithmetic operators is left-to-right, and for comparison operators is right-to-left.
  • 55. Associativity (2) • Now, if we have a look at this code: var x = 1; var y = 2; var z = 3; y += x *= z; • The value of x, y and z after the last operation depends on whether x *= z or y += x is executed first. • As we have two assignment operators, and their associativity is right-to-left, we know what will be the order in which they will be analysed.
  • 57. Statements • Statements are instructions that tell the interpreter to perform an action. • You have already seen some examples of statements in: x = 1; counter --;
  • 58. Conditional statements: if • The if statement allows you to test an expression and then make a branch in the script’s flow of control • You can nest if statements, obtaining multi-way branches
  • 59. Conditional statements: if (2) if (number == 1) { // first branch: // applicable if number is '1' } else { if (number == 2) { // second branch: // applicable if number is '2' } else { // optional 'catch all' branch // statements applicable if number is not '1' or '2’ } }
  • 60. Activity #4: if… else… • Ask the user whether s/he would want to receive the mailing list of the website (confirm()). • If the users accepts, ask for the email address (prompt()) and inform (alert()) the user he has been registered • Otherwise, thanks the user anyway (alert())
  • 61. Conditional statements: switch • If all the branches depend on the same expression it is more efficient and clearer to use a switch statement
  • 62. Conditional statements: switch (2) switch(number) { case 1: // statements applicable if number is '1’ break; case 2: // statements applicable if number is '2’ break; default: // optional 'catch all' branch break; }
  • 63. Activity #5: using switch • Refactor activity #4, implementing it again with switch
  • 64. Loop statements: for • The for statement is used to perform a sequence of one or more instructions a number of times • The general form of the for loop is: for ( [initialisation]; [test]; [increment] ) { [statement] } • The loop typically initialises a counter which is then tested against a terminating condition.
  • 65. Loop statements: while • The general form of the while loop is: while ( [test];) { [statement] }
  • 66. Debugging JavaScript • JavaScript code can be complex, and so it is important that one of the skills you acquire during this course is to be able to identify bugs in the code (this is called debugging).
  • 67. Activity #6: debugging JavaScript • Try to inspect the following code. <script type="text/javascript " > var hello_world = "Hello World; var text_to_alert = ""; for (var c=1; c<=5; c++) { text_to_alert += hello_word + ": " + c + " time.n"; } alert(text_to_alert); </script>
  • 68. Activity #6: debugging JavaScript (2) • There are two errors in the code (and a bonus error!); can you see them? – If you can see the errors – well done! It means that you are getting familiar with JavaScript syntax. • If you can’t see the errors, don’t worry. Open Firefox and install Firebug, if you haven’t done it yet. – Use the Firebug console and tools to identify the errors.
  • 70. Objects • Objects are a collection of properties, each of which has a name and a value • A property of an object is simply an additional piece of information held in the object about the object.
  • 71. Objects (2) • Objects are typically used when you need to structure information • To access the value of a property, you have to use a ‘dot’ notation, as we did in our Hello Word example: greeting.text = "Hello World";
  • 72. Functions • A function is a discrete set of instructions that carry out some task • Functions are used to group tasks and to re-use code – A function used inside a class is called method – We will see later what a class is and how to use them
  • 73. Functions (2) • This is a function stub in JavaScript: function nameOfTheFunction([parameter_1], [parameter_2], [parameter_3]) { // you can use parameter_1, parameter_2, parameter_3 in your statements // parameter_1, parameter_2, parameter_3 are local variables, valid // only inside the function [statements] }
  • 74. Functions (3) • This is how to invoke (or ‘call’) the function in the previous slide: nameOfTheFunction([parameter_a], [parameter_b], [parameter_c]); • The value of parameter_a will be passed to parameter_1, the value of parameter_b will be passed to parameter_2 and the value of parameter_c will be passed to parameter_3.
  • 75. Local and global variables • parameter_a, parameter_b, parameter_c are said to be global variables, while parameter_1, parameter_2, parameter_3 are called local variables, valid only inside the function.
  • 76. Local and global variables (example) function addNumber (number1, number2) { var number3 = number1 + number2; // the next line returns the value of total back // to the global context // otherwise it would not be available any more return number3; } var number3 = addNumber(3,5);
  • 77. Variable scope • The scope of a variable is the region of code where it is defined and may be used. – A ‘global’ variable has global scope: it can be accessed anywhere in a script. – Other variables such as those declared within a function are ‘local’ variables and may only be accessed within the function. – Local variable names take precedence over those with greater scope.