Vous êtes sur la page 1sur 90

JavaScript

Introduction
• JavaScript is the programming language of
HTML and the Web.
• JavaScript is one of the 3 languages all web
developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web
pages
• JavaScript is:
– JavaScript is a lightweight, interpreted
programming language
– Designed for creating network-centric applications
– Complementary to and integrated with Java
– Complementary to and integrated with HTML
– Open and cross-platform
<script> tag
• A JavaScript consists of JavaScript statements that
are placed within the <script>... </script> HTML
tags in a web page.
• You can place the <script> tag containing your
JavaScript anywhere within you web page but it is
preferred way to keep it within the <head> tags.
• Syntax
<script ...> JavaScript code </script>
• JavaScript is a case-sensitive language.
• The script tag takes two important attributes:
language: This attribute specifies what scripting
language you are using. Typically, its value will
be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this
attribute.
type: This attribute is what is now recommended to
indicate the scripting language in use and its value
should be set to "text/javascript".
• So your JavaScript segment will look like:
<script language="javascript" type="text/javascript">
JavaScript code </script>
First JavaScript Script

• <html>
<body>
<script language="javascript“ type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
• Here, we call a function document.write which writes a
string into our HTML document. This function can be used
to write text, HTML, or both. So above code will display
following result:
Hello World!
Comments in JavaScript

• JavaScript supports both C-style and C++-style


comments, Thus:
– Any text between a // and the end of a line is
treated as a comment and is ignored by JavaScript.
– Any text between the characters /* and */ is
treated as a comment. This may span multiple
lines.
• Most preferred ways to include JavaScript in
your HTML file
– Script in <head>...</head> section.
– Script in <body>...</body> section.
– Script in <body>...</body> and <head>...</head>
sections.
– Script in and external file and then include in
<head>...</head> section.
JavaScript in External File

• Example to show how you can include an external JavaScript file in your
HTML code using script tag and its src attribute:
<html>
<head>
<script type="text/javascript“ src="filename.js" ></script>
</head>
<body> ....... </body>
</html>
• To use JavaScript from an external file source, you need to write your all
JavaScript source code in a simple text file with extension ".js" and then
include that file as shown above.
• For example, you can keep following content in filename.js file and then
you can use sayHello function in your HTML file after including filename.js
file:
function sayHello() { alert("Hello World") }
JavaScript DataTypes

• JavaScript allows you to work with three primitive


data types:
– Numbers eg. 123, 120.50 etc.
– Strings of text e.g. "This text string" etc.
– Boolean e.g. true or false.
• JavaScript also defines two trivial data
types, null and undefined, each of which defines
only a single value.
• In addition to these primitive data types,
JavaScript supports a composite data type known
as object.
JavaScript Variables

• Variables can be thought of as named containers. You can place


data into these containers and then refer to the data simply by
naming the container.
• Before you use a variable in a JavaScript program, you must declare
it. Variables are declared with the var keyword as follows:
<script type="text/javascript">
var money;
var name;
</script>
• You can also declare multiple variables with the same var keyword
as follows:
<script type="text/javascript">
var money, name;
</script>
• You might create a variable named money and assign the
value 2000.50 to it later. For another variable you can
assign a value the time of initialization as follows:
<script type="text/javascript">
var name = "Ali";
var money;
money = 2000.50;
</script>
• JavaScript is untyped language. This means that a
JavaScript variable can hold a value of any data type. Unlike
many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable
will hold.
JavaScript Variable Names

• While naming your variables in JavaScript keep


following rules in mind.
– You should not use any of the JavaScript reserved keyword
as variable name. These keywords are mentioned in the
next section. For example, break or boolean variable
names are not valid.
– JavaScript variable names should not start with a numeral
(0-9). They must begin with a letter or the underscore
character. For example, 123test is an invalid variable name
but_123test is a valid one.
– JavaScript variable names are case sensitive. For
example, Name and name are two different variables.
Escape Sequences
Javascript Operators
Arithmetic Operators

++ Increment
-- Decrement
Decision Making: Equality and
Relational Operators
JavaScript Assignment Operators

Operator Example Same As


= x=y x=y
+= x += y x= x + y
-= x -= y x=x-y
*= x *= y x= x * y
/= x /= y x= x / y
%= x %= y x= x % y
JavaScript String Operators

• The + operator can also be used to add


(concatenate) strings.
• When used on strings, the + operator is called the
concatenation operator.
• Example
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;
The result of txt3 will be:
John Doe
• JavaScript has dynamic types. This means that
the same variable can be used as different
types:
• Example
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
• Strings are written with quotes. You can use
single or double quotes.
• JavaScript objects are written with curly braces.
• Object properties are written as name:value
pairs, separated by commas.
• Example
var person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
The object (person) in the example above has 4
properties: firstName, lastName, age, and
eyeColor.
The typeof Operator

• You can use the JavaScript typeof operator to find


the type of a JavaScript variable:
• Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
• In JavaScript, an array is a special type of object.
Therefore typeof [1,2,3,4] returns object.
Undefined variable and Empty values
• In JavaScript, a variable without a value, has the
value undefined. The typeof is also undefined.
• Example
var person; // Value is undefined,
//type is undefined
• An empty value has nothing to do with undefined.
• An empty string variable has both a value and a type.
• Example
var car = ""; // The value is "", the typeof is
//string
Null

• In JavaScript null is "nothing". It is supposed to be


something that doesn't exist.
• Unfortunately, in JavaScript, the data type of null is an
object.
• You can empty an object by setting it to null:
• Example
var person = null; // Value is null, but
//type is still an object
• You can also empty an object by setting it to undefined:
• Example
var person = undefined; // Value is undefined, type is
//undefined
• JavaScript if...else Statements
– JavaScript supports following forms of if..else statement:
• if statement
• if...else statement
• if...else if... statement.
• JavaScript Switch Case
– Javascript also supports switch case statement.
• Javascript loops
– While
– Do while
– For
• Javascript also supports break and continue statements.
Javascript : Functions
• Modules in JavaScript are called functions.
• The prepackaged functions that belong to
JavaScript objects (such as Math.pow and
Math.round, introduced previously) are often
called methods.
• The term method implies that the function
belongs to a particular object.
• The programmer can write functions to define
specific tasks that may be used at many
• points in a script. These functions are referred to
as programmer-defined functions.
Function Definition
• The format of a function definition is
function function-name( parameter-list)
{
declarations and statements
}
The function-name is any valid identifier. The parameter-list is
a comma-separated list containing the names of the
parameters received by the function when it is called.
There should be one argument in the function call for each
parameter in the function definition. If a function does not
receive any values, the parameter-list is empty (i.e., the
function name is followed by an empty set of parentheses).
• The declarations and statements within braces
form the function body. The function body is
also referred to as a block. A block is a
compound statement that includes
declarations. The terms block and compound
statement often are used interchangeably.
Return statement
• There are three ways to return control to the point at
which a function was invoked.
• If the function does not return a result, control returns
when the program reaches the function ending right
brace or by executing the statement
return;
• If the function does return a result, the statement
return expression;
returns the value of expression to the caller. When a
return statement is executed, control returns
immediately to the point at which the function was
invoked.
JavaScript Global Functions
Recursion vs. Iteration
• Both iteration and recursion are based on a control
structure: Iteration uses a repetition structure (such as
for, while or do/while); recursion uses a selection
structure (such as if, if/else or switch).
• Both iteration and recursion involve repetition:
Iteration explicitly uses a repetition structure; recursion
achieves repetition through repeated function calls.
• Iteration and recursion each involve a termination test:
Iteration terminates when the loop-continuation
condition fails; recursion terminates when a base case
is recognized.
• Iteration with counter-controlled repetition and
recursion both gradually approach termination:
Iteration keeps modifying a counter until the counter
assumes a value that makes the loop-continuation
condition fail; recursion keeps producing simpler
versions of the original problem until the base case is
reached.
• Both iteration and recursion can occur infinitely: An
infinite loop occurs with iteration if the loop-
continuation test never becomes false; infinite
recursion occurs if the recursion step does not reduce
the problem each time via a sequence that converges
on the base case, or if the base case is incorrect.
Arrays
• An array is a group of memory locations that all
have the same name and normally are of the
same type.
• To refer to a particular location or element in the
array, we specify the name of the array and the
position number of the particular element in the
array.
• The first element in every array is the zeroth
element.
• The position number in square brackets is called a
subscript(or an index).
Declaring and Allocating Arrays
• Actually, an array in JavaScript is an Array
object.
• The programmer uses operator new to
allocate dynamically the number of elements
required by each array.
• The process of creating new objects is also
known as creating an instance, or instantiating
an object, and operator new is known as the
dynamic memory allocation operator.
• If the values of an Array’s elements are known in advance,
the elements of the Array can be allocated and initialized in
the declaration of the array.
• There are two ways in which the initial values can be
specified. The statement
var n = [ 10, 20, 30, 40, 50];
uses a comma-separated initializer list enclosed in square
brackets ([ and ]) to create a five element Array with
subscripts of 0, 1, 2, 3and 4. The array size is determined by
the number of values in the initializer list.
• The preceding declaration does not require the new
operator to create the Array object.
• The statement
var n = new Array( 10, 20, 30, 40, 50);
also creates a five-element array with
subscripts of 0, 1, 2, 3and 4. In this case, the
initial values of the array elements are
specified as arguments in the parentheses
following new Array.
• The size of the array is determined by the
number of values in parentheses.
• It is also possible to reserve a space in an
Array for a value to be specified later by using
a comma as a place holder in the initializer
list. For example, the statement
var n = [ 10, 20, , 40, 50];
creates a five-element array with no value
specified for the third element (n[2]).
Array length property
• Every array know its length.
• length property returns the number of
elements in an array.
• Syntax – array.length
• Example
var fruits=["Banana", "Orange", "Apple", "Man
go"];
document.write(fruits.length);
• The result will be 4.
Array join() method
• The join() method joins the elements of an array into a
string, and returns the string.
• The elements will be separated by a specified
separator. The default separator is comma (,).
• Syntax - array.join(separator)
• Example -
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join();
The result of energy will be:
Banana,Orange,Apple,Mango
• Try using a different separator:
var fruits=["Banana", "Orange", "Apple", "Man
go"];
var energy = fruits.join(" and ");
The result of energy will be:
Banana and Orange and Apple and Mango
for/in control structure
• This control structure enables a script to perform
a task for each element in an object. Syntax:
for (variable name in object)
{
statement or block to execute
}
• In each iteration one property from object is
assigned to variablename and this loop continues
till all the properties of the object are exhausted.
• Example:
• ar p = {f:“po", l:”ji", a:”op”};
• var text = ""; var x;
• for (x in p)
{
• text += p[x] ;
• }
document.getElementById("demo").innerHTML =
text;
• Inside the parentheses, we declare the element
variable used to select each element in the object
to the right of keyword in.
• JavaScript automatically determines the
number of elements in the object. As the
JavaScript interpreter iterates over p’s
elements, variable element is assigned a value
that can be used as a subscript for p.
• Each value of the object is concatenated by”+”
operator and final text is given to the variable
text.
References and Reference Parameters
• Two ways to pass arguments to functions (or methods)
in many programming languages are call-by-value and
call-by-reference (also called pass-by-value and pass-
by-reference).
• When an argument is passed to a function using call-
by-value, a copy of the argument’s value is made and is
passed to the called function.
• With call-by-value, changes to the called function’s
copy do not affect the original variable’s value in the
calling function.
• In JavaScript, numbers and boolean values are passed
to functions by value.
• With call-by-reference, the caller gives the called
function direct access to the caller’s data and to modify
those data if the called function so chooses. This
procedure is accomplished by passing to the called
function the actual location in memory(also called the
address) where the data resides.
• In JavaScript, all objects and Arrays are passed to
functions by reference. Objects are not passed to
functions; rather, references to objects are passed to
functions. When a function receives a reference to an
object, the function can manipulate the object directly.
• Unlike some other languages, JavaScript does not
allow the programmer to choose whether to pass
each argument by value or by reference.
• When returning information from a function via a
return statement, numbers and boolean values
are always returned by value (i.e., a copy is
returned), and objects are always returned by
reference (i.e., a reference to the object is
returned).
• To pass a reference to an object into a function, simply
specify in the function call the reference name.
Normally, the reference name is the identifier that the
program uses to manipulate the object.
• Mentioning the reference by its parameter name in the
body of the called function actually refers to the
original object in memory, and the original object can
be accessed directly by the called function.
• The name of an array actually is a reference to an
object that contains the array elements and the length
variable, which indicates the number of elements in
the array.
Passing Arrays to Functions
• To pass an array argument to a function, specify the name
of the array (a reference to the array) without brackets.
• For example, if array hourlyTemperatures has been
declared as
var hourlyTemperatures = new Array(24);
then the function call
modifyArray( hourlyTemperatures );
passes array hourlyTemperatures to function modifyArray.
• In JavaScript, every array object “knows” its own size (via
the length attribute). Thus, when we pass an array object
into a function, we do not pass the size of the array
separately as an argument.
• Although entire arrays are passed by using call-by-
reference, individual numeric and Boolean array
elements are passed by call-by-value exactly as simple
numeric and boolean variables are passed. Such simple
single pieces of data are called scalars,or scalar
quantities.
• For a function to receive an Array through a function
call, the function’s parameter list must specify a
parameter that will refer to the Array in the body of the
function.
• JavaScript simply requires that the identifier for the
Array be specified in the parameter list.
• For example, the function header for function
modifyArray might be written as
function modifyArray( b )
indicating that modifyArray expects to receive a
parameter named b (the argument supplied in
the calling function must be an Array).
• Because arrays are passed by reference, when the
called function uses the array name b, it refers to
the actual array in the caller (array
hourlyTemperatures in the preceding call).
• 1 and 2 initialize b[0][0] and b[0][1], and 3 and
4 initialize b[1][0] and b[1][1].
• The declaration
var b = [ [ 1, 2], [ 3, 4, 5] ];
creates array b with row 0 containing two
elements (1and 2) and row 1 containing three
elements (3, 4 and 5).
Javascript Objects
Math Object
• For example, a programmer desiring to
calculate and display the square root of 900.0
might write
document.writeln( Math.sqrt( 900.0) );
The result will be 30.0
Mathematical constants(properties) of
math object
String Object
• Example:
var s=“city”;
var t=s.concat(“lawns”);
The value of t variable will be concatenation of
2 strings- city and lawns, i.e., citylawns.
Date Object
• JavaScript’s Date object provides methods for
date and time manipulations.
• Date and time processing can be performed
based on the computer’s local time zone or
based on World Time Standard’s Universal
Coordinated Time (UTC)—formerly called
Greenwich Mean Time (GMT).
• Most methods of the Date object have a local
time zone and a UTC version.
• Example:
var t=new Date();
document.write(t.getHours())
will display the current hour in 24 hours
format.
Boolean and Number Objects
• JavaScript provides the Boolean and Number objects as
object wrappers for boolean true/false values and
numbers, respectively.
• JavaScript programmers can create Boolean objects
explicitly with the statement
var b = new Boolean(booleanValue);
The constructor argument booleanValue specifies whether
the value of the Boolean object should be true or false. If
booleanValue is false, 0, null, Number.NaN or the
empty string (""), or if no argument is supplied, the new
Boolean object contains false. Otherwise, the new Boolean
object contains true.
Methods of Boolean Object
• JavaScript programmers can create a Number
object with the statement
var n = new Number(numericValue);
The constructor argument numericValue is the
number to store in the object.
Methods and Properties of the
Number object
Window Object

• The window object represents an open


window in a browser.
• If a document contain frames (<iframe> tags),
the browser creates one window object for
the HTML document, and one additional
window object for each frame.
• 2 main methods
– alert()
– prompt()
Window alert() Method

• The alert() method displays an alert box with a


specified message and an OK button.
• An alert box is often used if you want to make
sure information comes through to the user.
• Syntax
alert(message)
• Parameter message is of type String which is
Optional. It specifies the text to display in the
alert box, or an object converted into a string and
displayed.
Example
<html>
<body>
<p>Click the button to display an alert box.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("Hello! I am an alert box!");
}
</script>
</body>
</html>
Window prompt() Method

• The prompt() method displays a dialog box that


prompts the visitor for input.
• A prompt box is often used if you want the user to
input a value before entering a page.
• When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after entering an
input value.
• The prompt() method returns the input value if the
user clicks "OK". If the user clicks "cancel" the method
returns null.
• Syntax
prompt(text, defaultText)
• Parameter text is of type String which is
required. It specifies the text to display in the
dialog box.
• Parameter defaultText is of type String which
is Optional. It specifies the default input text.
• If the user clicks OK without entering any text,
an empty string is returned.
Example
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML ="Hello " + person + "! How
are you today?";
}
}
</script>
</body>
</html>
Document object
• When an HTML document is loaded into a web
browser, it becomes a document object.
• The document object is the root node of the HTML
document and the "owner" of all other nodes:(element
nodes, text nodes, attribute nodes, and comment
nodes).
• The document object provides properties and methods
to access all node objects, from within JavaScript.
• Main methods
– getElementById()
– write()
– writeln()
HTML DOM getElementById() Method

• The getElementById() method returns the element that


has the ID attribute with the specified value.
• This method is one of the most common methods in
the HTML DOM, and is used almost every time you
want to manipulate, or get info from, an element on
your document.
• Returns null if no elements with the specified ID exists.
• An ID should be unique within a page. However, if
more than one element with the specified ID exists, the
getElementById() method returns the first element in
the source code.
• Syntax
document.getElementById(elementID)
• Parameter elementID is of type String which is
Required. It specifies the ID attribute's value
of the element you want to get.
Example
<html>
<body>
<p id="demo">Click the button to change the text in this
paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
write() Method

• The write() method writes HTML expressions or JavaScript code to


a document.
• The write() method is mostly used for testing: If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
• Syntax
document.write(exp1,exp2,exp3,...)
• Parameter exp1,exp2,exp3,... is Optional. It specifies what to write to
the output stream. Multiple arguments can be listed and they will be
appended to the document in order of occurrence.
• The writeln() method is identical to the document.write() method,
with the addition of writing a newline character after each statement.
Example
<html>
<body>
<script>
document.write("Hello World!");
</script>
</body>
</html>
Strings
Example
var text1 = "Hi";
var text2 = "Hello!";
var text2 = text2.toLowerCase();
var text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML
= text3;

Vous aimerez peut-être aussi