Department of Information
Communication Technology
Java Scripts
What is Java Script
JavaScript is a lightweight, interpreted programming language with
object-oriented capabilities
It is most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and
make dynamic pages.
It is designed for creating network-centric applications.
It is very easy to implement because it is integrated with HTML.
It is open and cross-platform.
It already installed on every modern web browser(e.g. internet
explorer, Chrome, Mozilla Firefox), thus no special environment setup
is required.
Javascript is used to create websites.
It has now extended been extended to mobile app development,
desktop app development, and game development. This opens many
opportunities for you as Javascript Programmer.
Application of Java Script
Client side validation - Java script is used to verify any user input at
the client end before submitting it to the server.
Manipulating HTML Pages - Javascript helps in manipulating HTML
page on the fly. This helps in adding and deleting any HTML tag very
easily using javascript and modify your HTML to change its look and
feel based on different devices and requirements.
User Notifications - It used to raise dynamic pop-ups on the
webpages to give different types of notifications to website visitors.
Presentations - it provides the facility of creating presentations
which gives website look and feel.
Server Applications - Node JS is built on Chrome's Javascript runtime
for building fast and scalable network applications. This is an event
based library which helps in developing very sophisticated server
applications including Web Servers.
Prerequisites
Prerequisite of Java script is the knowledge of HTML coding
is required.
Basic knowledge of object-oriented programming concepts is also
needed
Client-Side JavaScript
Client-side JavaScript is executed when the user submits the form,
and only if all the entries are valid, they would be submitted to the
Web Server.
JavaScript can be used to trap user-initiated events such as button
clicks, link navigation, and other actions that the user initiates
explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before
sending the page off to the server. This saves server traffic, which
means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a
page reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react
when the user hovers over them with a mouse or activates them
via the keyboard.
Richer interfaces − JavaScript can be used to create drag-and-
drop components and sliders to give a Rich Interface to site
visitors.
Java Script Elements
<Script > element used to define the beginning and the end of
java script program.
-It is placed withing Html tags
The <script> tag alerts the browser program to start interpreting
the text as a script whereas </script> alerts the browser program
to stop interpreting the text a script.
<script> tags, containing JavaScript, can be placed anywhere
within a within html web page, but it is recommended to place
them within the <head> tags.
Syntax
<Script> Element
Attributes of <script > element are two of them :
Language attribute specifies the name of scripting language being
used. Typically, its value should be set to “ javascript”.
Type attribute specifies the type of scripting language in use.
Typically, its value should be set to "text/javascript".
Example
<Script> Element
<Script >Element :
Example
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in
JavaScript programs.
spaces, tabs, and newlines can be placed in program to format
and indent the code for easy reading and understand.
However, the formatting will not appear when the script is
executed.
JavaScript Variables
JavaScript variables are containers (memory spaces) for storing
values.
Variables must be declared(created) using var keyword before
they are used .
Syntax var variableName;
• Example1
Example2: Multiple variables can be declared the same var keyword as follows
Variable initialization
Variable initialization refers to storing the initial value in a
variable.
This can be done at the time of variable creation or at a later
point in time when the variable is needed.
Syntax:
var carName = "Volvo";
Example :
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is
defined.
JavaScript variables have only two scopes.
Global Variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables is visible only within a function where it is defined.
Function parameters are always local to that function.
Example
JavaScript Variable Names
Variable Names are defined using the following names:
1. JavaScript reserved names are not used as variable name.
These keywords are mentioned in the next section. For
example, break or boolean variable names are not valid.
2. JavaScript variable names should not start with a numeral (0-
9).
3. They must begin with a letter or an underscore character. For
example, 123test is an invalid variable name but _123test is a
valid one.
JavaScript variable names are case-sensitive. For
example, Name and name are two different variables.
JavaScript Reserved Words
JavaScript reserved word refers to words that part of javaScript
core language.
They cannot be used as JavaScript variables, functions, methods,
loop labels, or any object names.
Examples
Functions
A function is a group of reusable code which can be called
anywhere in your program.
This eliminates the need of writing the same code again and
again.
Functions allow dividing a big program into a number of small
and manageable functions.
Defining a function
A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and
dollar signs (same rules as variables).
The parentheses may include parameter names separated by
commas if they are more than one: (parameter1, parameter2, ...)
Parameters are memory spaces specified after the function inside
the parenthess and they are used for passing values to a function
The code to be executed, by the function, is placed inside curly
brackets: {}
Syntax
Defining a function
Example1
The following example defines a function called sayHello that
has no parameters
Defining a functiom
Example2
The following example defines a function called Showmessage
that has two parameters
Using a Function
Using a Function involves calling the function by specifying its
name and passing arguments if it was defined using parameters
Syntax Function name (arguments)
Arguments are values that will be passed to parameters
For example1:
The following code calls sayHello() function so that it can execute
its code.
Out put:
The code produces the following output once executed
Using a Function
Example 2
The following code calls ShowMessage function and passes two
arguments
Output
The code produces the following output once executed
Defining and using Functions Example
Example: The following code shows java script code within a html code.
The javascript code creates within head section of html document
defines a function called sayhello(), that has two parameters (name,
age) and the java script within body section of html document calls the
sayHello() function and passes two arguments (‘zara’,7)
Function Return
Return statement is used to do the following two operations:
1. To terminate(exit) an executing function
2. To provide the final computed value after produced by the
terminating function. This value is "returned" back to the "caller“.
that is the calling program or function
A function with return statement can be defined as follows:
function name()
{
return value;
};
Function Return
Example
The following java script, defines a function called myfunction()
With two parameters(a and b), which returns the product of
arguments (4 and 3) that will be passed in them.
Function Return
Example2
The following java script defines a function called Sum()with two
parameters(val1,val2) and calls it using two arguments(10,20)
The sum () function returns the sum of adding the two arguments
The returned sum are the assigned or stored in result variable
Objects
JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it provides
four basic capabilities to developers −
Encapsulation − the capability to store and enclose related
information(data or methods), together in an object.
Aggregation − the capability to store(contain) one object inside
another object.
Inheritance − the capability of a class to derive properties and
methods from another class (or number of classes) for some of its
properties and methods.
Polymorphism − the capability to write one function or method
that works in a variety of different ways.
Objects
Object is unique instance of a class.
It is composed of the following components:
[Link] are the values(data) of an object that is stored by object
property that is defined in the class of the object.
2. behavior is a set of operations (actions) performed on the state
by the object. The operations are implemented by methods that
are defined in the class of an object.
2. Name of object is the unique identity of an object.
Creating an object
Javascripts Objects are created using a constructor and new operator
New operator is used to create an instance of an object.
To create an object, the new operator is followed by the constructor
method.
A constructor is a function that creates and initializes an object.
JavaScript provides a special constructor function called Object() to
create an object.
Example
Creating an Object
Example: The following example shows how to create an object
As indicated in the above example, the properties assigned to the
object are not variables. Therefore, they are not defined with
the var keyword.
Creating an object
An object can also be created with other built-in JavaScript
constructors such as Array(), and Date().
Example
Object Properties
Object Properties are used to store values(state) about object.
Syntax:
Example:
The following code gets the document title using the "title“
property of the document object.
Object Methods
Methods are the functions that enable an object to perform
operations or allow operations to be done to it.
The difference between a function and a method is that a
function is a standalone unit of statements and a method is
attached to an object and can be referenced by the this keyword.
objects and methods Example 1
Write and execute the following JavaScript program
Output
<HTML>
<HEAD>
<TITLE>Some Document</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
// script statements
</SCRIPT>
<NOSCRIPT>
<B>Your browser has JavaScript turned off.</B><BR>
You will experience a more enjoyable time at this Web site if you turn JavaScript on.
<HR>
</NOSCRIPT>
</HEAD>
<BODY>
<H2>The body of your document.</H2>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Some Document</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
// script statements
</SCRIPT>
function today()
{
var days = new Array(“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,
“Friday”,”Saturday”)
var today = new Date()
return days[[Link]()]
}
Object Methods
Methods are useful for everything from displaying the contents of the
object to the screen to performing complex mathematical operations
on a group of local properties and parameters.
For instance , Write() function can be used to display the state(data)
of an object properties
Example1
The above example show how to use the write() method of
document object to write any content on the document.
Example 2
The above code prints contents of Subject and author properties of
book object
Defining Methods for an Object
Defining a Method entails to creating a function and attached it to
an object and can be referenced by the “this” keyword.
this keyword refers to the object that has been passed to a function.
Example
Output
Events
Event is an happening or action that occur when the progam is
executing.
For example, loading of a web page, clicking a button by the user,
that click too is an event, pressing any key, closing a window,
resizing a window, etc.
JavaScripts can be used to give responses when an event occurs
For example, display messages, validating user input etc.
Event Handler Assignments
<HTML>
<HEAD>
<SCRIPT LANGUAGE=”JavaScript”>
<!--
function doIt()
{
// statements
}
//-->
</SCRIPT></HEAD>
<BODY>
<FORM>
<INPUT TYPE=button NAME=janeButton VALUE=”Click Me”>
<SCRIPT LANGUAGE=”JavaScript1.1”>
<!--
[Link][0].[Link]=doIt
//-->
</SCRIPT>
</FORM>
</BODY>
</HTML>
JavaScript Events
There are several javascript events that can be executed against.
Examples
JavaScript Events: Onclick event
onclick Event Type, occurs left button of mouse is clicked.
Javascript can be written to validate , give warning etc., against this
event type.
Example
Output
References
[Link]
[Link]
[Link]