You are on page 1of 19

JavaScript Introduction

JavaScript is the most popular scripting language on the internet, and works in all major
browsers, such as Internet Explorer, Firefox, Chrome, pera, and Safari!
What is JavaScript?
JavaScript was designed to add interactivit" to #$%& pages
JavaScript is a scripting language
' scripting language is a lightweight programming language
JavaScript is usuall" embedded directl" into #$%& pages
JavaScript is an interpreted language (means that scripts execute without
preliminar" compilation)
Ever"one can use JavaScript without purchasing a license
What can a JavaScript do?
JavaScript gives HTML designers a programming tool - #$%& authors are
normall" not programmers, but JavaScript is a scripting language with a ver"
simple s"ntax* 'lmost an"one can put small +snippets+ of code into their #$%&
pages
JavaScript can put dynamic text into an HTML page - ' JavaScript statement
like this, document!write(+-h./+ 0 name 0 +-1h./+) can write a variable text into
an #$%& page
JavaScript can react to events - ' JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user clicks
on an #$%& element
JavaScript can read and write HTML elements - ' JavaScript can read and
change the content of an #$%& element
JavaScript can e used to validate data - ' JavaScript can be used to validate
form data before it is submitted to a server! $his saves the server from extra
processing
JavaScript can e used to detect the visitor!s rowser 2 ' JavaScript can be
used to detect the visitor3s browser, and 2 depending on the browser 2 load another
page specificall" designed for that browser
JavaScript can e used to create coo"ies 2 ' JavaScript can be used to store and
retrieve information on the visitor3s computer
The #eal $ame is %&M'Script
JavaScript3s official name is EC%'Script!
EC%'Script is developed and maintained b" the EC%' organi4ation!
%&M'-()( is the o**icial JavaScript standard+
$he language was invented b" 5rendan Eich at 6etscape (with 6avigator 7!8), and has
appeared in all 6etscape and %icrosoft browsers since .99:!
$he standard was approved as an international IS (IS1IEC .:7:7) standard in .99;!
JavaScript How To
$he #$%& -script/ tag is used to insert a JavaScript into an #$%& page!
,ut a JavaScript into an HTML page
$he example below shows how to use JavaSript to write text on a web page,
%xample
-html/
-bod"/
-script t"pe<+text1javascript+/
document!write(+#ello =orld*+)>
-1script/
-1bod"/
-1html/
$he example below shows how to add #$%& tags to the JavaScript,
%xample
-html/
-bod"/
-script t"pe<+text1javascript+/
document!write(+-h./#ello =orld*-1h./+)>
-1script/
-1bod"/
-1html/
%xample %xplained
$o insert a JavaScript into an #$%& page, we use the -script/ tag! Inside the -script/
tag we use the t"pe attribute to define the scripting language!
So, the -script t"pe<+text1javascript+/ and -1script/ tells where the JavaScript starts and
ends,
-html/
-bod"/
-script t"pe<+text1javascript+/
!!!
-1script/
-1bod"/
-1html/
$he document+write command is a standard JavaScript command for writing output to a
page!
5" entering the document!write command between the -script/ and -1script/ tags, the
browser will recogni4e it as a JavaScript command and execute the code line! In this case
the browser will write #ello =orld* to the page,
-html/
-bod"/
-script t"pe<+text1javascript+/
document!write(+#ello =orld*+)>
-1script/
-1bod"/
-1html/
JavaScript Where To
JavaScripts in the bod" section will be executed =#I&E the page loads!
JavaScripts in the head section will be executed when C'&&E?!
Where to ,ut the JavaScript
JavaScripts in a page will be executed immediatel" while the page loads into the browser!
$his is not alwa"s what we want! Sometimes we want to execute a script when a page
loads, other times when a user triggers an event!
Scripts in -head.
Scripts to be executed when the" are called, or when an event is triggered, go in the head
section!
If "ou place a script in the head section, "ou will ensure that the script is loaded before
an"one uses it!
%xample
-html/
-head/
-script t"pe<+text1javascript+/
function message()
@
alert(+$his alert box was called with the onload event+)>
A
-1script/
-1head/
-bod" onload<+message()+/
-1bod"/
-1html/
Scripts in -ody.
Scripts to be executed when the page loads go in the bod" section!
If "ou place a script in the bod" section, it generates the content of a page!
%xample
-html/
-head/
-1head/
-bod"/
-script t"pe<+text1javascript+/
document!write(+$his message is written b" JavaScript+)>
-1script/
-1bod"/
-1html/
Scripts in -head. and -ody.
Bou can place an unlimited number of scripts in "our document, so "ou can have scripts
in both the bod" and the head section!
-html/
-head/
-script t"pe<+text1javascript+/
!!!!
-1script/
-1head/
-bod"/
-script t"pe<+text1javascript+/
!!!!
-1script/
-1bod"/
/sing an %xternal JavaScript
If "ou want to run the same JavaScript on several pages, without having to write the same
script on ever" page, "ou can write a JavaScript in an external file!
Save the external JavaScript file with a !js file extension!
$ote0 $he external script cannot contain the -script/ tag*
$o use the external script, point to the !js file in the +src+ attribute of the -script/ tag,
%xample
-html/
-head/
-script t"pe<+text1javascript+ src<+xxx!js+/-1script/
-1head/
-bod"/
-1bod"/
-1html/
JavaScript Statements
JavaScript is a seCuence of statements to be executed b" the browser!
JavaScript is &ase Sensitive
Dnlike #$%&, JavaScript is case sensitive 2 therefore watch "our capitali4ation closel"
when "ou write JavaScript statements, create or call variables, objects and functions!
JavaScript Statements
' JavaScript statement is a command to a browser! $he purpose of the command is to tell
the browser what to do!
$his JavaScript statement tells the browser to write +#ello ?oll"+ to the web page,
document!write(+#ello ?oll"+)>
It is normal to add a semicolon at the end of each executable statement! %ost people
think this is a good programming practice, and most often "ou will see this in JavaScript
examples on the web!
$he semicolon is optional (according to the JavaScript standard), and the browser is
supposed to interpret the end of the line as the end of the statement! 5ecause of this "ou
will often see examples without the semicolon at the end!
$ote0 Dsing semicolons makes it possible to write multiple statements on one line!
JavaScript &ode
JavaScript code (or just JavaScript) is a seCuence of JavaScript statements!
Each statement is executed b" the browser in the seCuence the" are written!
$his example will write a heading and two paragraphs to a web page,
%xample
-script t"pe<+text1javascript+/
document!write(+-h./$his is a heading-1h./+)>
document!write(+-p/$his is a paragraph!-1p/+)>
document!write(+-p/$his is another paragraph!-1p/+)>
-1script/
JavaScript 1loc"s
JavaScript statements can be grouped together in blocks!
5locks start with a left curl" bracket @, and ends with a right curl" bracket A!
$he purpose of a block is to make the seCuence of statements execute together!
$his example will write a heading and two paragraphs to a web page,
%xample
-script t"pe<+text1javascript+/
@
document!write(+-h./$his is a heading-1h./+)>
document!write(+-p/$his is a paragraph!-1p/+)>
document!write(+-p/$his is another paragraph!-1p/+)>
A
-1script/
$he example above is not ver" useful! It just demonstrates the use of a block! 6ormall" a
block is used to group statements together in a function or in a condition (where a group
of statements should be executed if a condition is met)!
JavaScript &omments
JavaScript comments can be used to make the code more readable!
JavaScript &omments
Comments can be added to explain the JavaScript, or to make the code more readable!
Single line comments start with 11!
$he following example uses single line comments to explain the code,
%xample
-script t"pe<+text1javascript+/
11 =rite a heading
document!write(+-h./$his is a heading-1h./+)>
11 =rite two paragraphs,
document!write(+-p/$his is a paragraph!-1p/+)>
document!write(+-p/$his is another paragraph!-1p/+)>
-1script/
JavaScript Multi-Line &omments
%ulti line comments start with 1E and end with E1!
$he following example uses a multi line comment to explain the code,
%xample
-script t"pe<+text1javascript+/
1E
$he code below will write
one heading and two paragraphs
E1
document!write(+-h./$his is a heading-1h./+)>
document!write(+-p/$his is a paragraph!-1p/+)>
document!write(+-p/$his is another paragraph!-1p/+)>
-1script/
/sing &omments to ,revent %xecution
In the following example the comment is used to prevent the execution of a code block
(can e suitale *or deugging),
%xample
-script t"pe<+text1javascript+/
1E
document!write(+-h./$his is a heading-1h./+)>
document!write(+-p/$his is a paragraph!-1p/+)>
document!write(+-p/$his is another paragraph!-1p/+)>
E1
-1script/
/sing &omments at the %nd o* a Line
In the following example the comment is placed at the end of a code line,
%xample
-script t"pe<+text1javascript+/
document!write(+#ello+)> 11 =rite +#ello+
document!write(+ ?oll"*+)> 11 =rite + ?oll"*+
-1script/
JavaScript 2ariales
Fariables are +containers+ for storing information!
JavaScript 2ariales
's with algebra, JavaScript variables are used to hold values or expressions!
' variable can have a short name, like x, or a more descriptive name, like carname!
Gules for JavaScript variable names,
Fariable names are case sensitive (" and B are two different variables)
Fariable names must begin with a letter or the underscore character
$ote0 5ecause JavaScript is case2sensitive, variable names are case2sensitive!
%xample
' variable3s value can change during the execution of a script! Bou can refer to a variable
b" its name to displa" or change its value!
-html/
-bod"/
-script t"pe<+text1javascript+/
var firstname>
firstname<+#e+>
document!write(firstname)>
document!write(+-br 1/+)>
firstname<+$ove+>
document!write(firstname)>
-1script/
-p/$he script above declares a variable,
assigns a value to it, displa"s the value, changes the value,
and displa"s the value again!-1p/
-1bod"/
-1html/
3eclaring 4&reating5 JavaScript 2ariales
Creating variables in JavaScript is most often referred to as +declaring+ variables!
Bou can declare JavaScript variables with the var statement,
var x>
var carname>
'fter the declaration shown above, the variables are empt" (the" have no values "et)!
#owever, "ou can also assign values to the variables when "ou declare them,
var x<H>
var carname<+Folvo+>
'fter the execution of the statements above, the variable x will hold the value 6, and
carname will hold the value 2olvo!
$ote0 =hen "ou assign a text value to a variable, use Cuotes around the value!
'ssigning 2alues to /ndeclared JavaScript 2ariales
If "ou assign values to variables that have not "et been declared, the variables will
automaticall" be declared!
$hese statements,
x<H>
carname<+Folvo+>
have the same effect as,
var x<H>
var carname<+Folvo+>
#edeclaring JavaScript 2ariales
If "ou redeclare a JavaScript variable, it will not lose its original value!
var x<H>
var x>
'fter the execution of the statements above, the variable x will still have the value of H!
$he value of x is not reset (or cleared) when "ou redeclare it!
JavaScript 'rithmetic
's with algebra, "ou can do arithmetic operations with JavaScript variables,
"<x2H>
4<"0H>
Bou will learn more about the operators that can be used in the next chapter of this
tutorial!
JavaScript 7perators
< is used to assign values!
0 is used to add values!
$he assignment operator 8 is used to assign values to JavaScript variables!
$he arithmetic operator 0 is used to add values together!
"<H>
4<7>
x<"04>
$he value of x, after the execution of the statements above is I!
JavaScript 'rithmetic 7perators
'rithmetic operators are used to perform arithmetic between variables and1or values!
Jiven that y86, the table below explains the arithmetic operators,
7perator 3escription %xample #esult
0 'ddition x<"07 x<I
2 Subtraction x<"27 x<K
E %ultiplication x<"E7 x<.8
1 ?ivision x<"17 x<7!H
L %odulus (division remainder) x<"L7 x<.
00 Increment x<00" x<:
22 ?ecrement x<22" x<M
JavaScript 'ssignment 7perators
'ssignment operators are used to assign values to JavaScript variables!
Jiven that x89: and y86, the table below explains the assignment operators,
7perator %xample Same 's #esult
< x<" x<H
0< x0<" x<x0" x<.H
2< x2<" x<x2" x<H
E< xE<" x<xE" x<H8
1< x1<" x<x1" x<7
L< xL<" x<xL" x<8
The ; 7perator /sed on Strings
$he 0 operator can also be used to add string variables or text values together!
$o add two or more string variables together, use the 0 operator!
txt.<+=hat a ver"+>
txt7<+nice da"+>
txtK<txt.0txt7>
'fter the execution of the statements above, the variable txtK contains +=hat a ver"nice
da"+!
$o add a space between the two strings, insert a space into one of the strings,
txt.<+=hat a ver" +>
txt7<+nice da"+>
txtK<txt.0txt7>
or insert a space into the expression,
txt.<+=hat a ver"+>
txt7<+nice da"+>
txtK<txt.0+ +0txt7>
'fter the execution of the statements above, the variable txtK contains,
+=hat a ver" nice da"+
'dding Strings and $umers
$he rule is, I* you add a numer and a string< the result will e a string=
%xample
x<H0H>
document!write(x)>
x<+H+0+H+>
document!write(x)>
x<H0+H+>
document!write(x)>
x<+H+0H>
document!write(x)>
JavaScript &omparison and Logical
7perators
Comparison and &ogical operators are used to test for true or false!
&omparison 7perators
Comparison operators are used in logical statements to determine eCualit" or difference
between variables or values!
Jiven that x86, the table below explains the comparison operators,
7perator 3escription %xample
<< is eCual to x<<; is false
<<< is exactl" eCual to (value and type) x<<<H is true
x<<<+H+ is false
*< is not eCual x*<; is true
/ is greater than x/; is false
- is less than x-; is true
/< is greater than or eCual to x/<; is false
-< is less than or eCual to x-<; is true
How &an it e /sed
Comparison operators can be used in conditional statements to compare values and take
action depending on the result,
if (age-.;) document!write(+$oo "oung+)>
Logical 7perators
&ogical operators are used to determine the logic between variables or values!
Jiven that x8) and y8>, the table below explains the logical operators,
7perator 3escription %xample
NN and (x - .8 NN " / .) is true
OO or (x<<H OO "<<H) is false
* not *(x<<") is true
&onditional 7perator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition!
Syntax
variablename<(condition)Pvalue.,value7
Example
greeting<(visitor<<+QGES+)P+?ear Qresident +,+?ear +>
If the variable visitor has the value of +QGES+, then the variable greeting will be
assigned the value +?ear Qresident + else it will be assigned +?ear+!
JavaScript I*+++%lse Statements
Conditional statements are used to perform different actions based on different
conditions!
&onditional Statements
Fer" often when "ou write code, "ou want to perform different actions for different
decisions! Bou can use conditional statements in "our code to do this!
In JavaScript we have the following conditional statements,
i* statement 2 use this statement to execute some code onl" if a specified
condition is true
i*+++else statement 2 use this statement to execute some code if the condition is
true and another code if the condition is false
i*+++else i*++++else statement 2 use this statement to select one of man" blocks of
code to be executed
switch statement 2 use this statement to select one of man" blocks of code to be
executed
I* Statement
Dse the if statement to execute some code onl" if a specified condition is true!
Syntax
if (condition)
@
code to be executed if condition is true
A
6ote that if is written in lowercase letters! Dsing uppercase letters (IF) will generate a
JavaScript error*
%xample
-script t"pe<+text1javascript+/
11=rite a +Jood morning+ greeting if
11the time is less than .8
var d<new ?ate()>
var time<d!get#ours()>
if (time-.8)
@
document!write(+-b/Jood morning-1b/+)>
A
-1script/
6otice that there is no !!else!! in this s"ntax! Bou tell the browser to execute some code
only i* the speci*ied condition is true!
I*+++else Statement
Dse the if!!!!else statement to execute some code if a condition is true and another code if
the condition is not true!
Syntax
if (condition)
@
code to be executed if condition is true
A
else
@
code to be executed if condition is not true
A
%xample
-script t"pe<+text1javascript+/
11If the time is less than .8, "ou will get a +Jood morning+ greeting!
11therwise "ou will get a +Jood da"+ greeting!
var d < new ?ate()>
var time < d!get#ours()>
if (time - .8)
@
document!write(+Jood morning*+)>
A
else
@
document!write(+Jood da"*+)>
A
-1script/
I*+++else i*+++else Statement
Dse the if!!!!else if!!!else statement to select one of several blocks of code to be executed!
Syntax
if (condition1)
@
code to be executed if condition1 is true
A
else if (condition2)
@
code to be executed if condition2 is true
A
else
@
code to be executed if condition1 and condition2 are not true
A
%xample
-script t"pe<+text1javascript+/
var d < new ?ate()
var time < d!get#ours()
if (time-.8)
@
document!write(+-b/Jood morning-1b/+)>
A
else if (time/.8 NN time-.:)
@
document!write(+-b/Jood da"-1b/+)>
A
else
@
document!write(+-b/#ello =orld*-1b/+)>
A
-1script/
JavaScript Switch Statement
Conditional statements are used to perform different actions based on different
conditions!
The JavaScript Switch Statement
Dse the switch statement to select one of man" blocks of code to be executed!
Syntax
switch(n)
@
case .,
execute code block 1
break>
case 7,
execute code block 2
break>
default,
code to be executed if n is different from case 1 and 2
A
$his is how it works, First we have a single expression n (most often a variable), that is
evaluated once! $he value of the expression is then compared with the values for each
case in the structure! If there is a match, the block of code associated with that case is
executed! Dse rea" to prevent the code from running into the next case automaticall"!
%xample
-script t"pe<+text1javascript+/
11Bou will receive a different greeting based
11on what da" it is! 6ote that Sunda"<8,
11%onda"<., $uesda"<7, etc!
var d<new ?ate()>
the?a"<d!get?a"()>
switch (the?a")
@
case H,
document!write(+Finall" Frida"+)>
break>
case :,
document!write(+Super Saturda"+)>
break>
case 8,
document!write(+Sleep" Sunda"+)>
break>
default,
document!write(+I3m looking forward to this weekend*+)>
A
-1script/
JavaScript ,opup 1oxes
JavaScript has three kind of popup boxes, 'lert box, Confirm box, and Qrompt box!
'lert 1ox
'n alert box is often used if "ou want to ma"e sure in*ormation comes through to the
user+
=hen an alert box pops up, the user will have to click +R+ to proceed!
Syntax
alert(+sometext+)>
%xample
-html/
-head/
-script t"pe<+text1javascript+/
function showSalert()
@
alert(+I am an alert box*+)>
A
-1script/
-1head/
-bod"/
-input t"pe<+button+ onclick<+showSalert()+ value<+Show alert box+ 1/
-1bod"/
-1html/
&on*irm 1ox
' confirm box is often used if "ou want the user to verif" or accept something!
=hen a confirm box pops up, the user will have to click either +R+ or +Cancel+ to
proceed!
If the user clicks +R+, the box returns true! If the user clicks +Cancel+, the box returns
false!
Syntax
confirm(+sometext+)>
%xample
-html/
-head/
-script t"pe<+text1javascript+/
function showSconfirm()
@
var r8con*irm4?,ress a utton?5@
if (r<<true)
@
document!write(+Bou pressed R*+)>
A
else
@
document!write(+Bou pressed Cancel*+)>
A
A
-1script/
-1head/
-bod"/
-input t"pe<+button+ onclick<+showSconfirm()+ value<+Show confirm box+ 1/
-1bod"/
-1html/
,rompt 1ox
' prompt box is often used if "ou want the user to input a value before entering a page!
=hen a prompt box pops up, the user will have to click either +R+ or +Cancel+ to
proceed after entering an input value!
If the user clicks +R+ the box returns the input value! If the user clicks +Cancel+ the box
returns null!
Syntax
prompt(+sometext+,+defaultvalue+)>
%xample
-html/
-head/
-script t"pe<+text1javascript+/
function showSprompt()
@
var name<prompt(+Qlease enter "our name+,+#arr" Qotter+)>
if (name*<null NN name*<++)
@
document!write(+#ello + 0 name 0 +* #ow are "ou toda"P+)>
A
A
-1script/
-1head/
-bod"/
-input t"pe<+button+ onclick<+showSprompt()+ value<+Show prompt box+ 1/
-1bod"/
-1html/

You might also like