Introduction to
JavaScript
Topics
Why JavaScript?
What is JavaScript?
Including JavaScript in HTML
Hello World Example Script
JavaScript Comments
Dialogue boxes
Variable, keywords, opertaors
2
Why Study JavaScript?
JavaScript is one of the 3 languages all web
developers must learn:
HTML to define the content of web pages
CSS to specify the layout of web pages
JavaScript to program the behaviour of web
pages
3
Why Study JavaScript?
Once you learned JavaScript, it helps you develop great
front-end as well as back-end software using different
JavaScript-based frameworks like jQuery, [Link], etc.
JavaScript is used to create interactive websites.
perform calculations on the user's computer (ex: form
validation)
4
Why use client-side
programming?
PHP/JSP/ASP already allows us to create
dynamic web pages. Why also use client-side
scripting?
client-side scripting (JavaScript) benefits:
usability: can modify a page without having to
post back to the server (faster UI)
efficiency: can make small, quick changes to
page without waiting for server
event-driven: can respond to user actions like
clicks and key presses
CS380 5
Introduction
JavaScript scripting language
Enhances functionality and appearance
Client-side scripting
Makes pages more dynamic and interactive
Web browser contains a JavaScript interpreter.
It is an interpreted programming language with
object-oriented capabilities.
6
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
7
Including JavaScript in HTML
Two ways to add JavaScript to Web pages
Use the <script>…</script> tag
Include the script in an external file
8
Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)
9
1) JavaScript Example : code
between the body tag
10
Hello World in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
[Link]("<h1>Hello, world!</h1>");
</script>
</body>
</html>
11
Hello World Screenshot
12
The <script>…</script> tag
The code for the script is contained in the
<script>…</script> tag
<script type="text/javascript">
.
.
.
</script>
13
Displaying text
The [Link]() method writes a string
of text to the browser
<script type="text/javascript">
[Link]("<h1>Hello, world!</h1>");
</script>
14
[Link]()
Ends in a semicolon
[Link]("<h1>Hello,world!</h1>");
Enclosed in quotes --
denotes a "string"
15
Comments in JavaScript
Two types of comments
Single line
Uses two forward slashes (i.e. //)
Multiple line
Uses /* and */
16
Single Line Comment Example
<script type="text/javascript">
// This is my JavaScript comment
[Link]("<h1>Hello!</h1>");
</script>
17
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.
*/
[Link]("<h1>Hello!</h1>");
</script>
18
2) JavaScript Example :
code between the head
tag
19
3) External JavaScript file
We can create external JavaScriptfilese and embed it in many html page.
It provides code reusabilityty because single JavaScript file can be used in
several html pages.
An external JavaScript file must be saved by .js extension. It is recommended
to embed all JavaScript files into a single file. It increases the speed of the
webpage.
Advantages of External JavaScript
It helps in the reusability of code in more than one HTML file.
It allows easy code readability.
It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
The length of the code reduces as only we need to specify the location of
the js file.
20
3) External JavaScript file
21
HTML DOM Element innerHTML
22
Dialogue Boxes
JavaScript uses 3 kinds of dialog boxes:
ALERT, PROMPT and CONFIRM.
These dialog boxes can be used to raise and
alert, or to get confirmation on any input or
to have a kind of input from the users.
23
1) ALERT BOX:
An alert box is used on the website to show a
warning message to the user that they have
entered the wrong value other than what is
required to fill in that position.
Nonetheless, an alert box can still be used
for friendlier messages. The alert box gives
only one button “OK” to select and
24
1) ALERT BOX: Example
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" >
</form>
</body>
</html>
25
1) CONFIRM BOX:
A confirm box is often used if you want the
user to verify or accept something. When a
confirm box pops up, the user will have to
click either “OK” or “Cancel” to proceed.
If the user clicks on the OK button, the
window method confirm() will return true.
If the user clicks on the Cancel button, then
confirm() returns false and will show null.
26
1) CONFIRM BOX: Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to invoke the confirm().</p>
<button onclick="myFunction()">Click Here</button>
<p id="conf"></p>
<script>
function myFunction() {
var result;
var r = confirm("Select an Action!");
if (r == true) {
result = "You have selected OK!";
} else {
result = "You have selected Cancelled!";
}
[Link]("conf").innerHTML =
result;
}
</script>
</body>
</html> 27
1) Prompt/Input BOX:
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.
If the user clicks the OK button, the window
method prompt() will return the entered value
from the text box.
If the user clicks the Cancel button, the window
method prompt() returns null.
28
1) INPUT/PROMT BOX:
Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Value(){
var Val = prompt("Enter your name : ", "name");
[Link]("You entered : " + Val);
}
</script>
</head>
<body>
<p>Click me: </p>
<form>
<input type="button" value="Click Me" onclick="Value();" />
</form>
</body>
</html>
29
Programming with JavaScript (1)
document object: the XHTML document the
browser is currently displaying
A statement should end with a semicolon (;).
JavaScript is case sensitive.
writeln method writes a line in the
document
[Link](“<h1>Welcome</h1>”);
30
Programming with JavaScript (2)
Escape character ( \ )
Indicates “special” character is used in the string
window object : a browser window.
A Window object is created automatically with
every instance of a <body> or <frameset> tag
31
Escape sequences
Escape sequence Description
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line. Any characters output
after the carriage return overwrite the characters previously output on
that line.
\\ Backslash. Used to represent a backslash character in a string.
\" Double quote. Used to represent a double quote character in a string
contained in double quotes. For example,
[Link]( "\"in quotes\"" );
displays "in quotes" in an alert dialog.
\' Single quote. Used to represent a single quote character in a string. For
example,
[Link]( '\'in quotes\'' );
displays 'in quotes' in an alert dialog.
Fig Some common escape sequences.
32
Example:
• \n – Newline
"Hello\nWorld"
Output:
Hello
World
• \t – Horizontal Tab
Example:
"A\tB" → Output: A B (with spaces in between).
• \r – Carriage Return
Example:
"Hello\rHi" → Output: Hillo.
• \\ – Backslash
Example: "C:\\Users\\Name" → Output: C:\Users\Name.
• \" – Double Quote
Example:
[Link]("\"in quotes\"");
Displays: "in quotes".
• \' – Single Quote
Example:
[Link]('\'in quotes\'');
Displays: 'in quotes'. 33
Example
JavaScript:
[Link]( “<table border= \“1\” ” +
“width=\“50% \”> ” );
Result
<table border=“1” width=“50%”>
34
Variables
Variables are used to store data.
Keyword : var
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.
Name of a variable : a series of characters
letters, digits, underscores( _ ) and dollar signs ($)
no white space
not begin with a digit
not a keyword.
35
Use Variables
Declare a variable:
var name;
var size;
var name, size;
Assign a value to a variable:
name = “Lisa”;
size = 20;
Combine two steps:
var name = “Lisa”;
36
Dynamic Welcome Page
A script can adapt the content based on input
from the user or other variables
prompt method of window object
[Link](“Please enter your name”, “Shalini”);
37
Arithmetic
JavaScript performs arithmetic calculations.
Arithmetic operators:
Addition: numberOne + numberTwo
Subtraction: numberOne – 5
Multiplication: numberOne * numberTwo
Division: numberTwo / 6
Rules of operator precedence
a * ( b – c )
38
Adding Integers
Prompt user for two integers and calculate
the sum
parseInt method
Converts its string argument to an integer
Assignment statement
sum = number1 + number2;
If user types a non-integer value or clicks Cancel
button, a runtime logic error will occur.
NaN (not a number): “The sum is NaN”
39
<script type = "text/javascript">
var firstNumber, secondNumber, number1,number2, sum;
// read in first number from user as a string
firstNumber = [Link]( "Enter first integer", “0" );
// read in second number from user as a string
secondNumber = [Link]( "Enter second integer", "0" );
// convert numbers from strings to integers
number1 = parseInt( firstNumber );
number2 = parseInt( secondNumber );
// add the numbers
sum = number1 + number2;
// display the results
[Link]( "<h1>The sum is " + sum + "</h1><br><p>click Refresh
or (Reload) to run the script again</p>" );
</script>
40
41
Display Floating Point Number
toFixed() function
Example:
var number = 2;
[Link](“<h1>[Link](2)</h1>”;
Result:
2.00
42
Arithmetic
Many scripts perform arithmetic calculations
Expressions in JavaScript must be written in
straight-line form
Arithmetic
x--
y
Precedence of arithmetic
operators
Decision Making: Equality and
Relational Operators
Decision based on the truth or falsity of a
condition
Equality operators
Relational operators
Decision Making: Equality and
Relational Operators
Decision Making: Equality and
Relational Operators
JavaScript Objects
A javaScript object is an entity having state and
behavior (properties and method).
There are three ways to create a objects in
JavaScript.
1. By object literal
2. By creating instance of Object directly (using
new keyword)
3. By using an object constructor (using new
keyword)
49
1) JavaScript Object by object literal:
syntax
object={property1:value1,property2:value2.....propertyN:valu
eN}
Example-
2) By creating instance of Object(Using the new Keyword)
Syntax
var objectname=new Object();
Example-
50
3)By using an Object constructor
Here, you need to create function with arguments. Each
argument value can be assigned in the current object by
using this keyword.
• this is referring to the object being created when new
emp(...) is called.
• It assigns the value (id,name,salary)to the new object
properties.
51
Accessing Object Properties
You can access object properties in two ways:
1. [Link]
2. objectName["propertyName"]
52
Adding New Properties
You can add new properties to an existing object by
simply giving it a value.
53
Deleting Properties (delete keyword)
54
JavaScript Object Methods
A JavaScript object method is a function stored as a property of an object..
It allows objects to perform actions using their own properties.
55
Accessing Object Methods
You access an object method with the following syntax:
[Link]()
56
THANK YOU
59