2.
Coding the Front End,
JavaScript
What is JavaScript?
Created by Netscape
Originally called LiveWire then LiveScript
A client-side scripting language
Client-side refers to the fact that it is executed in
the client (software) that the viewer is using. In
the case of JavaScript, the client is the browser.
A server-side language is one that runs on the
Web server. Examples: PHP, Python
Interpreted on-the-fly by the client
Each line is processed as it loads in the browser
PREPARED BY: Dr. SUNITA PADMANNAVAR
JavaScript is not Java
Completely different types of languages that
just happen to be similarly named
JavaScript - programs are interpreted in the
browser
Java - programs are compiled and can be run as
stand alone applications
PREPARED BY: Dr. SUNITA PADMANNAVAR
Why JavaScript?
It’s easier to learn than most programming
languages
It allows you to make interactive Web pages
(For example: Form validation such as checking if an email
format is correct or not, Displaying a countdown clock,
Interactive maps, Creating cool animations, Different actions
on the press of the button, Use of dropdown menu)
It is also used in: Making server-side
applications (The Node.js provides an environment for
JavaScript to run on servers.), game development,
Creating mobile apps, web apps etc.
PREPARED BY: Dr. SUNITA PADMANNAVAR
Including JavaScript in HTML
Two ways to add JavaScript to Web pages
Use the <script>…</script> tag.
Include the script as external file.
JavaScript files have the file extension .js
External scripts cannot contain <script>tags.
<script src="myScript.js"></script>
PREPARED BY: Dr. SUNITA PADMANNAVAR
Hello World in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
document.write("<h1>Hello, world!</h1>");
</script>
</body>
</html>
PREPARED BY: Dr. SUNITA PADMANNAVAR
Hello World Screenshot
PREPARED BY: Dr. SUNITA PADMANNAVAR
The <script>…</script> tag
The code for the script is contained in the
<script>…</script> tag
<script type="text/javascript">
.
.
.
</script>
PREPARED BY: Dr. SUNITA PADMANNAVAR
Hiding JavaScript from Older
Browsers
Some older browsers do not support JavaScript
We need to tell those browsers to ignore what is in the
<script> tag
<script type="text/javascript">
<!--
some JavaScript code
//-->
</script> PREPARED BY: Dr. SUNITA PADMANNAVAR
Displaying text
The document.write() method writes a string
of text to the browser
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
PREPARED BY: Dr. SUNITA PADMANNAVAR
document.write()
Ends in a semicolon
document.write("<h1>Hello,world!</h1>");
Enclosed in quotes --
denotes a "string"
PREPARED BY: Dr. SUNITA PADMANNAVAR
Comments in JavaScript
Two types of comments
Single line
Uses two forward slashes (i.e. //)
Multiple line
Uses /* and */
PREPARED BY: Dr. SUNITA PADMANNAVAR
Single Line Comment Example
<script type="text/javascript">
<!--
// This is my JavaScript comment
document.write("<h1>Hello!</h1>");
//-->
</script>
PREPARED BY: Dr. SUNITA PADMANNAVAR
Multiple Line Comment
Example
<script type="text/javascript">
<!--
/* This is a multiple line comment.
* The star at the beginning of this line is optional.
* So is the star at the beginning of this line.
*/
document.write("<h1>Hello!</h1>");
//-->
</script>
PREPARED BY: Dr. SUNITA PADMANNAVAR
<script type="text/javascript">
<!--
/* This is my JavaScript comment
* that spans more than 1 line.
*/
document.write("<h1>Hello!</h1>");
//-->
</script> PREPARED BY: Dr. SUNITA PADMANNAVAR
Creating External JavaScript Files
Here are some things to note about using an
external JavaScript file:
» The file must use a plain text format.
» Use the .js extension when you name the file.
For example, if the file is named myscripts.js,
then your <script> tag set up as follows:
<script src="myscripts.js">
PREPARED BY: Dr. SUNITA PADMANNAVAR
Variables
A variable is a "container" for
information you want to store. A
variable's value can change during the
script. You can refer to a variable by
name to see its value or to change its
value.
PREPARED BY: Dr. SUNITA PADMANNAVAR
Rules for naming variables
JavaScript has only a few rules for variable names:
1. The first character must be a letter or an
underscore (_). You can’t use a number as the first
character.
2. The rest of the variable name can include any
letter, any number, or the underscore. You can’t use
any other characters, including spaces, symbols,
and punctuation marks.
3. As with the rest of JavaScript, variable names are
case sensitive.
4.There’s no limit to the length of the variable name.
5.You can’t use one of JavaScript’s reserved words as
a variable name (such as var, alert, or prompt etc).
PREPARED BY: Dr. SUNITA PADMANNAVAR
JavaScript var Vs let
Both var and let are used to declare variables.
However, there are some differences between
them.
var let
let is the new way of
var is used in the older
declaring variables
versions of JavaScript
starting ES6 (ES2015).
var is function scoped let is block scoped.
For example, var x; For example, let y;
PREPARED BY: Dr. SUNITA PADMANNAVAR
Declare a Variable
You can create a variable with the var statement:
var strname = some value
You can also create a variable without the var statement:
strname = some value
Assign a Value to a Variable
You can assign a value to a variable like this:
var strname = "Hege" Or strname = "Hello“
Lifetime of Variables
Local variables
Global variables PREPARED BY: Dr. SUNITA PADMANNAVAR
Data Types
A variable’s data type specifies what kind of data is stored
within the variable.
For example
todaysQuestion = "What color is your parachute?";
Integers Hexadecimal integer values
0; 42; 2001; -20; 0x23; 0xff; 0X10ce;
Floating-point numbers:
0.07; 3.14159 ; -16.6666667 ;
9.87654e+5; // Exponential notation
3.4567e-4;
string literals
"Web Coding and Development";
'August 23, 1959'; "";
PREPARED BY: Dr. SUNITA PADMANNAVAR
"What's the good word?";
If the notation contains a plus sign, then you multiply the first
part of the number (that is, the part before the e or E) by 10 to
the power of the exponent. The exponent is 5, and 10 to the
power of 5 is 100,000. So multiplying 9.87654 by 100,000
results in the value 987,654
If the notation contains a minus sign, instead, then you divide
the rest of the number by 10 to the power of the exponent.
Here’s an example: 3.4567e-4; The exponent is 4, and 10 to
the power of 4 is 10,000. So dividing 3.4567 by 10,000 results
in the value .00034567.
PREPARED BY: Dr. SUNITA PADMANNAVAR
<!DOCTYPE html>
<html>
<head>
<title>typeof Example</title>
</head>
<body>
<script type="text/javascript">
var a = 17;
var b = "GIT";
var c = "";
var d = null;
document.write("Type of a = " + (typeof a));
document.write("<br>");
document.write("Type of b = " + (typeof b));
document.write("<br>");
document.write("Type of c = " + (typeof c));
document.write("<br>");
document.write("Type of d = " + (typeof d));
document.write("<br>");
document.write("Type of e = " + (typeof e));
document.write("<br>"); PREPARED BY: Dr. SUNITA PADMANNAVAR
</script> </body> </html>
PREPARED BY: Dr. SUNITA PADMANNAVAR
Using quotation marks within strings
onsubmit="processForm('testing')“;
"This is "illegal" in JavaScript."; // illegal
escape sequences
The \" combination is called an escape sequence.
You can combine the backslash with a number of
other characters to form other escape sequences,
and each one enables the browser to represent a
character that, by itself, would be illegal or not
representable otherwise.
PREPARED BY: Dr. SUNITA PADMANNAVAR
For Example
alert("This is line 1.\nSo what. This is line 2.");
PREPARED BY: Dr. SUNITA PADMANNAVAR
Boolean literals
taskCompleted = true;
currentMonth === "August“
value of the currentMonth variable equal the
string "August“ then returns true else false
JavaScript and HTML Keywords
JavaScript keywords are reserved words.
Reserved words cannot be used as
names for variables.
PREPARED BY: Dr. SUNITA PADMANNAVAR
JavaScript Reserved Words
PREPARED BY: Dr. SUNITA PADMANNAVAR
Building Expressions
An expression is a collection of symbols, words,
and numbers that performs a calculation and
produces a result.
In expression the inputs are called operands,
and they’re combined by using special symbols
called operators.
Numeric Expressions
String Expressions
Comparison Expressions
Logical Expressions
PREPARED BY: Dr. SUNITA PADMANNAVAR
Numeric Expressions
Arithmetic Operators
PREPARED BY: Dr. SUNITA PADMANNAVAR
Operator1_prg.html program
PREPARED BY: Dr. SUNITA PADMANNAVAR
Arithmetic Assignment Operators
PREPARED BY: Dr. SUNITA PADMANNAVAR
String Expressions
var preTipTotal = 10.00;
var tipAmount = preTipTotal * 0.15;
var message1 = "Your tip is ";
var message2 = "\nYour total bill is ";
alert(message1 + tipAmount + message2 + preTipTotal +
tipAmount);
var preTipTotal = 10.00;
var tipAmount = preTipTotal * 0.15;
var totalBill = preTipTotal + tipAmount;
var message1 = "Your tip is ";
var message2 = "\nYour total bill is ";
alert(message1 + tipAmount + message2 + totalBill);
PREPARED BY: Dr. SUNITA PADMANNAVAR
Comparison Expressions
The identity operator (===) checks whether two operands are identical, which
means it checks not only that the operands’ values are equal, but also that the
operands are of the same data type. (Which is why the identity operator is also
PREPARED BY: Dr. SUNITA PADMANNAVAR
sometimes called the strict equality operator.)
let val1 = 5;
// Equality Operators
document.write(val1 == 5);
document.write("<br>");
// Relational Operators
document.write(val1 > 0);
Result=?
Result=?
PREPARED BY: Dr. SUNITA PADMANNAVAR
For example
var albumName = "1984";
var albumReleaseDate = 1984;
var result = albumName === albumReleaseDate;
// returns false
In the statements below, variable hasBugs contains the Boolean
value true and variable totalBugs contains a number. These
values are of different data types, so the expression
hasBugs !== totalBugs returns true:
var hasBugs = true;
var totalBugs = 1;
var result = hasBugs !== totalBugs;
PREPARED BY: Dr. SUNITA PADMANNAVAR
strings in comparison expressions
Example Output
"a" < "B" false
“B” comes before “a,”
"Smith" < "Smyth" True
The first two letters in each
string are the same, but the
third letters are different.
The internal value of the i in
Smith is less than the
internal value of the y
"Marg" > "Margaret“ False
"Marg " > "Margaret" the fifth “letter” of the left
operand is a space,
whereas the fifth letter of
"Margaret" is a.
PREPARED BY: Dr. SUNITA PADMANNAVAR
In JavaScript, by definition, the following values
are the equivalent of false:
» 0 (the number zero)
» "" (the empty string)
» null
» undefined (which is, say, the “value” of an
uninitialized variable)
Everything else is the equivalent of true.
PREPARED BY: Dr. SUNITA PADMANNAVAR
ternary (?:) operator
expression ? result_if_true : result_if_false
Condition ? Expression1 : Expression2
var screenWidth = 768;
var maxPortableWidth = 1024;
var screenType = screenWidth > maxPortableWidth ? "Desktop" : "Portable";
The ternary operator evaluates the test condition.
•If the condition is true, expression1 is executed.
•If the condition is false, expression2 is executed.
The ternary operator takes three operands, hence, the name ternary
operator. It is also knownPREPARED BY: Dr. SUNITA PADMANNAVAR
as a conditional operator.
let PMarks = 40
let result = (PMarks > 39)? "Pass":"Fail";
document.write(result);
Result=?
PREPARED BY: Dr. SUNITA PADMANNAVAR
Logical Expressions
PREPARED BY: Dr. SUNITA PADMANNAVAR
Truth Table for the AND (&&) Operator
Truth Table for the
NOT (!) Operator
Truth Table for the OR (||) Operator
PREPARED BY: Dr. SUNITA PADMANNAVAR
var finishedDinner = true;
var clearedTable = true;
var getsDessert = finishedDinner && clearedTable;
Result = ?
var haveWallet = true;
var haveKeys = false;
var canGoOut = haveWallet && haveKeys;
Result = ?
var hasFever = true;
var hasCough = false;
var missSchool = hasFever || hasCough;
Result = ?
var salesOverBudget = false;
var expensesUnderBudget = false;
var getsBonus = salesOverBudget ||
expensesUnderBudget;
PREPARED BY: Dr. SUNITA PADMANNAVAR
Result = ?
The JavaScript Order of Precedence for Operators
PREPARED BY: Dr. SUNITA PADMANNAVAR
var totalPrice = 11.00; var taxRate = .1; var
retailPrice = totalPrice / 1 + taxRate;
alert("The pre-tax price is " + retailPrice)
var totalPrice = 11.00; var taxRate = .1; var
retailPrice = totalPrice / (1 + taxRate);
alert("The pre-tax price is " + retailPrice);
PREPARED BY: Dr. SUNITA PADMANNAVAR