JAVASCRIPT
Javascript
HTML to define the content of web
pages
CSS to specify the layout of web
pages
JavaScript to program the behavior of
web pages
JavaScript
How do I get JavaScript?
Where can I download JavaScript?
Is JavaScript Free?
The <script> Tag
In HTML, JavaScript code is inserted
between <script> and </script> tags.
Old JavaScript examples may use a type
attribute: <script type="text/javascript">.
You can place any number of scripts in
an HTML document.
Scripts can be placed in the <body>, or
in the <head> section of an HTML page,
or in both.
The <script> Tag
Placing scripts at the bottom of the
<body> element improves the display
speed, because script interpretation slows
down the display.
Scripts can also be placed in external files
JavaScript files have the file extension .js.
External scripts cannot
contain <script> tags.
The <script> Tag
An external script can be referenced in 3
different ways:
With a full URL (a full web address)
With a file path (like /js/)
Without any path
JavaScript
JavaScript Can Change HTML Content
getElementById()
document.getElementById("demo").inne
rHTML = "Hello JavaScript";
JavaScript
JavaScript Can Change HTML Attribute
Values
JavaScript changes the value of
the src (source) attribute of
an <img> tag
<button
onclick="document.getElementById('myI
mage').src='pic_bulbon.gif'">Turn on the
light</button>
JavaScript
JavaScript Can Change HTML Styles
(CSS)
document.getElementById("demo").style
.fontSize = "35px";
JavaScript
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by
changing the display style
document.getElementById("demo").style
.display = "none";
JavaScript
Showing hidden HTML elements can
also be done by changing
the display style
document.getElementById("demo").style
.display = "block";
JavaScript Output
Writing to an HTML element, using innerHTML
<script>
document.getElementById("demo").innerHTML =
5 + 6;
</script>
Writing to HTML output, using document.write()
The document.write() method should only be used
for testing.
<script>
document.write(5 + 6);
</script>
JavaScript Output
Writing into an alert box,
using window.alert().
<script>
window.alert(5 + 6);
</script>
Writing into the browser console,
using console.log().
<script>
console.log(5 + 6);
</script>
JavaScript Print
JavaScript does not have any print object or
print methods.
You cannot access output devices from
JavaScript.
The only exception is that you can call
the window.print() method in the browser to
print the content of the current window.
<button onclick="window.print()">Print this
page</button>
JavaScript Keywords
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be
executed on a condition
switch Marks a block of statements to be
executed in different cases
for Marks a block of statements to be
executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of
statements
JavaScript Values
The JavaScript syntax defines two types
of values:
Fixed values
Variable values
Fixed values are called Literals.
Variable values are called Variables.
JavaScript Operators
arithmetic operators ( + - * / )
to compute values:
assignment operator ( = )
to assign values to variables:
JavaScript Expressions
An expression is a combination of
values, variables, and operators, which
computes to a value.
The computation is called an evaluation.
JavaScript Identifiers / Names
Identifiers are JavaScript names.
Identifiers are used to name variables and
keywords, and functions.
The rules for legal names are the same in most
programming languages.
A JavaScript name must begin with:
A letter (A-Z or a-z)
A dollar sign ($)
Or an underscore (_)
Subsequent characters may be letters, digits,
underscores, or dollar signs.
JavaScript Variable
4 Ways to Declare a JavaScript
Variable:
Using var
Using let
Using const
Using nothing
JavaScript Identifiers
Names can contain letters, digits,
underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _ (but
we will not use it in this tutorial)
Names are case sensitive (y and Y are
different variables)
Reserved words (like JavaScript
keywords) cannot be used as names
JavaScript Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
JavaScript Bitwise Operators
Operator Descriptio Example Same as Result Decimal
n
& AND 5&1 0101 & 0001 1
0001
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0100 4
0001
<< left shift 5 << 1 0101 << 1 1010 10
>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned 5 >>> 1 0101 >>> 1 0010 2
right shift
DOM
DOM
The W3C DOM standard is separated
into 3 different parts:
Core DOM - standard model for all
document types
XML DOM - standard model for XML
documents
HTML DOM - standard model for HTML
documents
DOM
The HTML DOM is a
standard object model
and programming interface
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML
elements
The events for all HTML elements
DOM
Property Description DOM
document.anchors Returns all <a> 1
elements that have a
name attribute
document.applets Deprecated 1
document.baseURI Returns the absolute 3
base URI of the
document
document.body Returns the <body> 1
element
document.cookie Returns the 1
document's cookie
document.doctype Returns the 3
document's doctype
document.documentEl Returns the <html> 3
ement element
Property Description DOM
document.documentMod Returns the mode used 3
e by the browser
document.documentURI Returns the URI of the 3
document
document.domain Returns the domain 1
name of the document
server
document.domConfig Obsolete. 3
document.embeds Returns all <embed> 3
elements
document.forms Returns all <form> 1
elements
document.head Returns the <head> 3
element
document.images Returns all <img> 1
elements
Property Description DOM
document.implementa Returns the DOM 3
tion implementation
document.inputEncodi Returns the 3
ng document's encoding
(character set)
document.lastModified Returns the date and 3
time the document was
updated
document.links Returns all <area> and 1
<a> elements that
have a href attribute
document.readyState Returns the (loading) 3
status of the document
Property Description DOM
document.referrer Returns the URI of the 1
referrer (the linking
document)
document.scripts Returns all <script> 3
elements
document.strictErrorC Returns if error 3
hecking checking is enforced
document.title Returns the <title> 1
element
document.URL Returns the complete 1
URL of the document
object
Escape sequences
Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
Date
new Date(year, month, ...) creates a new
date object with a specified date and
time.
7 numbers specify year, month, day,
hour, minute, second, and millisecond
Eg:const d
= new Date(2018, 11, 24, 10, 33, 30, 0);
Date
6 numbers specify year, month, day,
hour, minute, second
Eg: const d
= new Date(2018, 11, 24, 10, 33, 30);
5 numbers specify year, month, day,
hour, and minute
Eg: const d
= new Date(2018, 11, 24, 10, 33);
JavaScript Date Formats
Type Example
ISO Date "2015-03-25" (The International
Standard)
Short Date "03/25/2015"
Long Date "Mar 25 2015" or "25 Mar 2015"
Get Date Methods
Method Description
getFullYear() Get the year as a four digit number
(yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since
January 1, 1970)
getDay() Get the weekday as a number (0-
6)
Date.now() Get the time. ECMAScript 5.
Set Date Methods
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and
day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since
January 1, 1970)
Regular Expression Modifiers
perform case-insensitive more global searches
Modifier Description
I Perform case-insensitive matching
g Perform a global match (find all
matches rather than stopping after
the first match)
m Perform multiline matching
Regular Expression Patterns
to find a range of characters
Expression Description
[abc] Find any of the
characters between
the brackets
[0-9] Find any of the digits
between the brackets
(x|y) Find any of the
alternatives
separated with |
Metacharacters are characters with a
special meaning
Metacharacter Description
\d Find a digit
\s Find a whitespace
character
\b Find a match at the
beginning of a word
like this: \bWORD, or
at the end of a word
like this: WORD\b
\uxxxx Find the Unicode
character specified
by the hexadecimal
number xxxx
Quantifiers define quantities
Quantifier Description
n+ Matches any string
that contains at least
one n
n* Matches any string
that contains zero or
more occurrences of n
n? Matches any string
that contains zero or
one occurrences of n
JSON
JSON is a format for storing and
transporting data.
JSON is often used when data is sent
from a server to a web page.
JSON stands
for JavaScript Object Notation
JSON is a lightweight data interchange
format
JSON Syntax Rules
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
The file type for JSON files is ".json"
The MIME type for JSON text is
"application/json"
JSON Values
In JSON, values must be one of the following data
types:
a string
a number
an object
an array
a boolean
null
In JavaScript values can be all of the above, plus
any other valid JavaScript expression, including:
a function
a date
undefined
JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe"
},
{ "firstName":"Anna", "lastName":"Smit
h" },
{ "firstName":"Peter", "lastName":"Jone
s" }
]}
XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</
lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</
lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</
lastName>
</employee>
</employees>
JSON is Like XML Because
Both JSON and XML are "self
describing" (human readable)
Both JSON and XML are hierarchical
(values within values)
Both JSON and XML can be parsed and
used by lots of programming languages
Both JSON and XML can be fetched
with an XMLHttpRequest
JSON is Unlike XML Because
JSON doesn't use end tag
JSON is shorter
JSON is quicker to read and write
JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML
parser. JSON can be parsed by a
standard JavaScript function
Why JSON is Better Than XML
XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript
object.
For AJAX applications, JSON is faster and
easier than XML:
Using XML
○ Fetch an XML document
○ Use the XML DOM to loop through the document
○ Extract values and store in variables
Using JSON
○ Fetch a JSON string
○ JSON.Parse the JSON string
Valid Data Types
In JSON, values must be one of the
following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
JSON values cannot be one of the
following data types:
a function
a date
undefined
Exception handling
Exception handling is one of the
powerful JavaScript features to handle
errors and maintain a regular JavaScript
code/program flow.
it discovers where the problem occurred.
Errors occur due to mistakes made by
developers, wrong input, or
unforeseeable things.
why exceptions occur
Dividing a number by zero: This results
in infinity, thus throwing an exception.
When a requested file does not exist in
the system.
When the user provides the wrong input.
When the network drops during
communication.
JavaScript error types
Syntax Errors: These are errors that cannot
be interpreted by the computer. These errors
stop the program from working.
In JavaScript, these errors are:
Spelling errors (wrong spelling such as
fiction instead of function).
The omission of important characters, such
as not using a semicolon to end a statement.
Use of the wrong indentation.
JavaScript error types
Runtime Errors: These errors take place
during execution. The errors get detected
when your program runs. It crashes or
raises an exception. Thus, exception
handlers handle exception errors.
These errors are often caused by:
The program not being able to find data
because it does not exist.
The data being an invalid type of data
JavaScript error types
Logical Errors: These types of errors
do not throw an error or an exception at
all. This is because they result from the
code not doing what the developer
intends it to. It’s challenging to find
logical errors. They can only be found
through thorough testing.
Error object properties
The error object has two properties:
Name: It gives the error name.
Message: It sets or returns the error
message in the form of a string.
Error objects
EvalError: The EvalError function
indicates the error that occurred in the
eval() function. It’s a global function that
evaluates the JavaScript string
RangeError: RangeError exceptions
occur when a numeric value is outside
the specified range.
ReferenceError:
A ReferenceError exception occurs
when undeclared variables are used
Error objects
Syntax Error: A Syntax Error exception
occurs when JavaScript language rules get
broken.
TypeError: A TypeError exception occurs
when a value is different from the one
expected.
URIError: A URIError exception is raised
by encodeURI() and decodeURI() methods.
Exception Handling
Throw, and Try...Catch...Finally
The try statement defines a code block
to run (to try).
The catch statement defines a code
block to handle any error.
The finally statement defines a code
block to run regardless of the result.
The throw statement defines a custom
error.
try-catch
try-catch-finally