CIM 322 Topic 2 JavaScript Fundamentals
CIM 322 Topic 2 JavaScript Fundamentals
Topic 2: JavaScript
Fundamentals
1
Lecture Overview
2
Introduction to JavaScript
• A client-side interpreted, object-oriented and
event-driven scripting language.
• It was first introduced in Netscape Navigator
and named LiveScript.
• The name changed to JavaScript 1.0 with the
release of Navigator 2.0.
• Later Microsoft released Internet Explorer 4.0
with a version of JavaScript named Jscript.
3
• The 2 versions differed so greatly that
programmers were forced to write different
applications for the 2 browsers.
• To avoid similar problems in the future, an
international standardized version of
JavaScript called ECMAScript, was created.
• Its most recent version is edition ES6.
4
JavaScript Capabilities
i. Turn static web pages into applications such as
games or calculators.
ii. Change the contents of a web page after a
browser has rendered it.
iii. Create visual effects such as animation.
iv. Control the web browser window itself.
v. Work with information such as device
orientation, speed, and geolocation reported by
web-connected devices.
5
JavaScript Security Issues
• For security reasons JavaScript has several
limitations set on its operations:
1.Cannot be used outside the web browser.
2.Cannot run system commands or execute
programs on a client.
3.Can only manipulate select files associated
with the browser.
6
4. Access in the client is limited to reading and
writing cookies and a few other types of
browser storage.
5. JavaScript cannot interact directly with web
servers that operate at the processing tier.
7
Components
of a JavaScript Application
8
1. HyperText Markup Language (HTML) - is used
to define the content and structure of a web
page.
2. Cascading Style Sheets ( CSS) are used to
control how web pages are displayed by
specifying the fonts, colors, borders, spacing,
and layout of the pages.
3. JavaScript – used to do the client-side
processing e.g. user input validation
9
JavaScript Development Tools
• Aptana Studio 3 (Windows and Mac)
• Komodo Edit (Windows and Mac)
• Notepad++ (Windows)
• TextWrangler (Mac) etc.
10
Embedding JavaScript to an HTML
Document
• JavaScript code is placed between the <script>
and </script> tags.
• Example:
<script>
document.bgColor=“red”;
</script>
• The <script> tag tells the browser that the
scripting engine must interpret the commands it
contains.
11
JavaScript Basic Syntax
1. JavaScript Block
• A block of JavaScript Code must be enclosed
between the <script> and </script> HTML
tags.
• Example:
<script>
document.write(“Hello Africa”);
</script>
12
2. Reserved word
• JavaScript native Keywords are reserved and
cannot be used for any other purpose e.g.
variable names.
• Examples: var, document, write, instanceof,
typeof etc.
3. Case sensitivity
• JavaScript is case sensitive
• N/B: All reserved words must be in lower case.
13
4. Identifiers
• Identifiers may be one or more characters in
the following format:
a) The first character must be a letter, an
underscore (_), or a dollar sign ($).
b) All other characters may be letters,
underscores, dollar signs, or numbers.
• By convention, identifiers use camel case:
firstName, myCar etc.
14
5. Comments
• A single-line comment begins with two forward-
slash characters:
//single line comment
• A block comment begins with a forward slash and
asterisk (/*) and ends with the opposite (*/) e.g.:
/*
* This is a multi-line
* Comment
*/
15
6. Strict Mode
• ECMAScript 5 introduced the concept of strict
mode.
• Strict mode addresses some erratic behavior
of earlier versions and throws errors for
unsafe activities.
• To enable strict mode for an entire script,
include the following at the top: “use strict”;
16
7. Semicolons are optional
• Executable statements in ECMAScript may or
may not be terminated by a semicolon.
example:
document.write(“Hello Africa”);
document.write(“Hello Africa”); (recommended)
17
JavaScript Variables
Variable Declaration
• Variable: a named storage location in the
primary memory.
• Syntax:
var variableName
• Example:
var fName;
var fNum;
18
Rules for Variable Naming
1. Variable names cannot contain spaces.
2. Variable names must begin with a letter, an
underscore (_) or a dollar sign ($).
3. Variable names can only contain letters,
numbers, underscores, or dollar signs.
4. Variable names are case-sensitive
19
JavaScript Primitive Data Types
• Data type: a specific value category.
• Primitive types: Data types assigned to a
single value.
20
The null Data Type
• It is both a data type and a value.
• It can be assigned to a variable.
• It indicates no usable value.
• Use: it is used to ensures that a variable does
not contain any data value.
21
Undefined Variable
• A variable that has never had a value assigned
to it, has not been declared, or does not exist.
• Undefined data indicates that the variable has
never been assigned a value: not even null.
• Use: it is used to determine if a value is being
used by another part of a script.
22
Assigning Values to a Variable
• Examples:
var stateTax;
document.write(stateTax);
stateTax = 40;
document.write(stateTax);
stateTax = null;
document.write(stateTax);
23
• JavaScript does not require you to declare
variable data type.
• Hence its a loosely /duck typed language.
• Loosely typed languages - Programming
languages that do not require you to declare
the data types of variables.
• A loosely typed language is also known as
dynamically typed, because data types can
change after they have been declared.
24
• JavaScript interpreter automatically
determines data type stored in a variable
• Examples:
diffTypes = "Hello World"; // String
diffTypes = 8; // Integer number
diffTypes = 5.367; // Floating-point number
diffTypes = true; // Boolean
diffTypes = null; // Null
25
• Strongly typed programming languages require
declaration of the data types of variables
• Strong typing is also known as static typing
• Static typing means that variable types cannot
change after it has been declared.
• Loosely typed programming languages do not
require declaration of the data types of variables
• Loose typing also known as dynamic typing
• Dynamic typing means that data types can
change after a variable has been declared
26
The typeof Operator
• Because ECMAScript is loosely typed, there needs
to be a way to determine the data type of a given
variable.
• The typeof operator provides that information.
• returns one of the following strings:
• “undefined” if the value is undefined
• “boolean” if the value is a Boolean
• “string” if the value is a string
27
• “number” if the value is a number
• “object” if the value is an object (other than a
function) or null “function” if the value is a
function
• Example:
var message = “some string”;
alert(typeof message); //string
28
JavaScript Dialog (Popup) Boxes
• 3 types:
i. Alert box
ii. Confirm box
iii. Prompt box
1. Alert Box
• Used to ensure information is passed to the user.
• the user will have to click "OK" to proceed.
• Syntax:
alert("text");
• Example:
Alert(“Invalid input”);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<script>
alert("You have entered an invalid value!");
</script>
</body>
</html>
32
Confirm Box
• used to ask the user to verify or accept
something.
• the user will have to click either "OK" or
"Cancel" to proceed.
• If the user clicks "OK", the box returns value
true.
• If the user clicks "Cancel", the box returns
value false.
• Syntax:
variableName=confirm("sometext");
• Example:
var flag = confirm(“Next?”);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<script>
var flag = confirm("Next?");
</script>
</body>
</html>
36
Prompt box
• used prompt a user to input a value.
• user will have to click either "OK" or "Cancel" to
proceed.
• "OK" the box returns the input value.
• "Cancel" the box returns the null value.
• Syntax:
variableName=prompt("sometext","defaultvalue");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt Box</h2>
<script>
var name = prompt("Please enter your name");
</script>
</body>
</html>
39
Data Type Converters
• Values captured using the prompt dialog box and
other HTML5 elements are string data.
• There are JS 2 methods used to convert string
data to numbers:
1. parseInt
• Converts a string to an integer.
• If it can't convert the string to an integer, it
returns NaN (Not a Number) value.
• Example: var num = parseInt(age);
40
2. parseFloat
• Converts string to a floating point number.
• If it can't convert the string to a decimal value,
it returns NaN (Not a Number) value.
• Example:
Var radius = parseFloat(rad);
Var radius =parseFloat(prompt(“Enter radius”);
41
Working with Numerical Values
• JavaScript supports two numeric data types:
Integers and floating-point numbers.
• Integer: positive or negative number with no
decimal places.
• Floating-point number: number containing
decimal places or written in exponential notation
• Exponential notation (scientific notation): a
shortened format for writing very large numbers
or numbers with many decimal places
42
Building Expressions
Arithmetic Binary operators
• They perform mathematical calculations.
• They return the modulus of a calculation
43
• Division operator (/)
– Standard mathematical division operation
• Modulus operator (%)
– Returns the remainder resulting from the division
of two integers.
• Example:
var divisionResult = 15 / 6; //2.5
var modulusResult = 15 % 6; // 3
44
• The assignment statement can include a
combination of variables and literal values on
the right side.
• However, it cannot include a literal value as
the left operand
• JavaScript interpreter attempts to convert the
string values to numbers.
• However, it does not convert strings to
numbers when using the addition operator
45
Arithmetic Unary Operators
• Arithmetic operations performed on a single
variable.
46
• The increment (++) and decrement (--) unary
operators can be used as prefix or postfix
operators.
• Prefix operator: an operator placed before a
variable name.
• Postfix operator: an operator placed after a
variable name.
47
• with the prefix operator, the value of the
operand is returned after it is increased or
decreased by a value of 1.
• with the postfix operator, the value of the
operand is returned before it is increased or
decreased by a value of 1.
48
• Examples:
var studentID = 100;
var curStudentID;
curStudentID = ++studentID; // assigns '101’
49
Assignment Operators
• An assignment operator “=“is used for
assigning a value to a variable.
• Example:
var x = 5;
50
Compound assignment operators
• Are used to perform mathematical
calculations on variables and literal values in
an expression then assign a new value to the
left operand.
51
52
• The += compound addition assignment
operator is used to combine two strings and to
add numbers.
• Example:
x = "5";
y = "4";
x += y; // a numeric value of 9 is returned for x
53
Conditional (Ternary) Assignment Operator
• The operator assigns a value to a variable
based on some condition.
Syntax:
variablename = (condition) ? value1:value2
Example:
mark = 45;
var remark = (mark>=40)? “Pass”: “Fail”; //
54
• Example App:
55
<!DOCTYPEhtml>
<html>
<head>
<title>Remark App</title>
</head>
<body>
<h1 align="center">Score Processing</h1>
<script>
//Input a score
var mark = parseInt(prompt("Enter a score in CIM 322"));
var remark = (mark >= 40)? "Proceed": "Halt";
// Output the results
document.write("Score:", mark, "<br />");
document.write("Remark:", remark, "<br />");
document.write("Thanks for using the <b>Exam Processing</b> App");
</script>
</body>
</html>
56
Operator Precedence
• Operator precedence – the order in which
operations in an expression are evaluated.
• Operators Associativity – determines the
order in which operators of equal precedence
execute.
• Associativity is evaluated from left-to-right or
right-to-left, depending on the operators
involved.
57
Operator Precedence Table
Rank Operator Description Associativity
1 ++ Increment Right to left
2 -- Decrement Right to left
3 * / % Multiplication/division/ Left to right
modulus
4 + - Addition/concatenation Left to right
and subtraction
58
Evaluating Associativity
• Example: multiplication and division operators
have an associativity of left to right
59
• In contrast, assignment operator and
compound assignment operators have an
associativity of right to left
• Example:
x = y *= ++x
var x = 3;
var y = 2;
x = y *= ++x;
60
Working with String Data
• Text string - contains zero or more characters
• It is surrounded by double or single quotation
marks.
• It can be used as literal constants or assigned
to a variable.
• Example:
var name =‘John’;
Document.write(“John”);
61
• Empty string - zero-length string value
• It is considered valid for literal strings
• It is not considered to be null or undefined.
• Example:
var customerName = "";
62
• Surround the quoted string with single
quotation marks
• To include a quoted string within a literal
string surrounded by single quotation marks
• Surround the quoted string with double
quotation marks
• String must begin and end with the same type
of quotation marks
63
• Examples:
document.write("<h1>Speech at the Berlin Wall↵
(excerpt)</h1>");
document.write("<p>Two thousand years ago, the
proudest boast↵
was 'civis Romanus sum.'<br />");
document.write('Today, in the world of freedom, the
proudest↵
boast is "Ich bin ein Berliner."</p>');
var speaker = "<p>John F. Kennedy</br>";
var date = 'June 26, 1963</p>';
document.write(speaker);
document.write(date);
64
• Output:
65
String operators
1. The Concatenation operator (+):
• combines two strings together to form one.
• Example:
var destination = "Honolulu";
var location = "Hawaii";
destination = destination + " is in " + location;
66
2. The Compound assignment operator (+=)
• Combines two strings together to form one.
var destination = "Honolulu";
destination += " is in Hawaii";
• N/B: Both operators apply to numbers also.
67
Escape Characters and Sequences
• Escape character - tells the compiler or
interpreter that the character that follows has a
special purpose.
• In JavaScript, the escape character is backslash (\)
• Escape sequence - Escape character combined
with other characters.
• Most escape sequences carry out special
functions.
68
69
• Example:
document.write("<p>My personal files are in
C:\\Users\\me\\Documents\\.</p>"); // Backslash
document.write(("<p>Written letters are sometimes called
\"snail mail.\"</p>")); // Double quotation mark
document.write('<p>India\'s capital is New
Delhi.</p>’); // Single quotation mark
70
JavaScript Variable Input Options
• There are 4 options for passing data into
JavaScript variables:
i. By initialization
• Example:
var x=5;
ii. By Processing
• Example:
Var x=mark1 + mark2;
71
iii). Using the prompt dialog box
• Example:
var name=prompt(“Enter name”);
//Output results
document.write("Heading Value:", val1, "<br />");
document.write("Paragraph Value:", val2, "<br />");
</script>
</body>
</html>
74
JavaScript Output Options
• JavaScript can "display" data in 4 different ways:
i. Writing into an HTML element, using innerHTML.
ii. Writing into the HTML output using
document.write().
iii.Writing into an alert box, using window.alert().
iv.Writing into the browser console, using
console.log().
75
1. Using innerHTML() Method
• Example:
document.getElementById(“p1").inner
HTML = ”Hello Africa”;
76
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var total=5+6;
document.getElementById("demo").innerH
TML = total;
</script>
</body>
</html>
77
2. Using window.alert() Dialog Box
<!DOCTYPE html>
<html>
<body>
<script>
var total=5+6;
window.alert(total);
</script>
</body>
</html
78
3. Using console.log() Method
• For debugging purposes, you can call the
console.log() method in the browser to display
data.
• Example:
79
<!DOCTYPE html>
<html>
<body>
<script>
var total=5+6;
console.log(total);
</script>
</body>
</html>
80
Adding Precision to Floating point
Numbers
• JS floating point arithmetic is not always 100%
accurate because it is done in binary.
• Example:
var x = 0.2 + 0.1; // 0.30000000000004
• JavaScript programmers use multiplication and
division as a shorthand for formatting decimal
numbers.
• Example:
var y = (0.2*10 + 0.1*10) / 10; // 0.3
81
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Decimal Numbers</h2>
<script>
var x = 0.2 + 0.1;
var y = (0.2*10 + 0.1*10) / 10;
document.write("0.2 + 0.1 = " , x);
document.write("<br />");
document.write("0.2 + 0.1 = " , y);
</script>
</body>
</html>
82
• Output:
83
Structuring JavaScript Code
• You can add JavaScript code just about
anywhere in a document.
• However, there are a number of factors to
consider in deciding the best location for
particular code e.g. if the code is to be reused
84
1. Including a script Element for Each Code
Section
• You can include as many script sections as you
like within a document.
• However, each section must include a <script>
and </script> pair.
85
2. Placing JavaScript in the Document Head or
Document Body
• You can place script elements in either the
document head or the document body, or in
both.
• However, in general, script elements are usually
placed at the end of the body section, just before
the closing </body> tag.
• Statements in head section can cause a delay in
the web page opening.
86
• This is because most browsers stop rendering
the rest of page until it finishes processing the
script.
• Placing JS code at the end allow browsers to
render all the simple HTML content
immediately on the user’s screen.
• Placing a JS code in the head section becomes
necessary when you have to declare a
function.
87
3. Creating a JavaScript Source File
• JavaScript code can be placed in an external
file called a JavaScript source file.
• You can then write a statement in the HTML
document that references the code saved in
the source file.
• When a browser encounters a reference to a
JavaScript source file, it loads the JavaScript
source file and executes the code it contains.
88
Locating Errors Using the Browser
Console
• Unintentional coding mistakes keep code from
working.
• Browsers generate error messages in response
• Error messages are displayed in browser
console pane.
• Error messages are hidden by default to avoid
alarming users.
• However, developers can display browser
console to see errors.
89
• Different browsers use different steps
90
• Consoles specify a line number with each
error
91
JavaScript Libraries
• Libraries: especially useful generic scripts used
on different websites.
• Often developed by single programmer or
team of programmers.
• Many available for free reuse
92
• Common libraries
a) Node.js
b) Backbone.js
• The 2 contain tools for creating and managing
large web applications.
c). Modernizr - is widely used to enable web
authors to deliver a consistent design and
functionality across different browsers, browser
versions, and platforms.
93