[go: up one dir, main page]

0% found this document useful (0 votes)
3 views19 pages

WT Ii

This document provides an overview of JavaScript, covering its introduction, functions, arrays, objects, and the advantages and limitations of the language. It explains the concept of programmer-defined functions, random number generation, and the use of modules in JavaScript for code organization and reusability. Additionally, it includes sample code snippets demonstrating various JavaScript functionalities and their applications.

Uploaded by

latag16024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

WT Ii

This document provides an overview of JavaScript, covering its introduction, functions, arrays, objects, and the advantages and limitations of the language. It explains the concept of programmer-defined functions, random number generation, and the use of modules in JavaScript for code organization and reusability. Additionally, it includes sample code snippets demonstrating various JavaScript functionalities and their applications.

Uploaded by

latag16024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

MCA II Sem UNIT-2

UNIT- 2

Java Script: Introduction to Scripting: Introduction – A Sample Program: Printing a Line of Text in a
Web Page – Obtaining user with prompt Dialogs

Functions: Introduction – Program Modules in JavaScript – Programmer-Defined Functions – Function


Definitions – Random Number Generation – Example – Scope Rules – JavaScript Global Functions–
Recursion vs. Iteration

Arrays: Declaring and Allocating Arrays – Examples Using Arrays – References and Reference
Parameters – Passing Arrays to Functions – Sorting Arrays – Searching Arrays : Linear Search and
Binary Search – Multidimensional Arrays.

Objects: Introduction – Thinking About Objects – Math Object – String Object – Date Object –
Boolean, Number, document, window Object

What is Java Script?


JavaScript is an “interpreted or dynamic computer programming language. It is lightweight and
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 an interpreted programming language with object-oriented
capabilities.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web
browsers.
● Complementary to and integrated with Java.
● JavaScript is the client side scripting language.
● Complementary to and integrated with HTML.
● Open and cross-platform.
● JavaScript code can be written in any text editor.
● If we write independently JavaScript code we save the file with an extension of “.js”.
● JavaScript is case sensitive programming language.
● JavaScript is platform independent language.
Advantages of JavaScript:
⮚ Less server interaction: You can validate user input before sending the page off to the server.
This saves server traffic, which means fewer loads 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: You can use JavaScript to include such items as drag-and-drop components
and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript:
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features:

Page 1
MCA II Sem UNIT-2

● Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
● JavaScript cannot be used for networking applications because there is no such support available.
● JavaScript doesn't have any multithreading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.
Disadvantages of JavaScript:
❖ Most Script rely upon manipulating the elements of the DOM. Support for a standard set of
objects currently doesn’t exist and access to objects differs from browser to browser.
❖ If your script doesn’t work then your page is useless, because of the problems of broken scripts
many web surfers disable JavaScript support in their browser.
❖ Scripts can run slowly and complex scripts can take a long time to start up.
Syntax:<script language="javascript" type="text/javascript">
JavaScript code
</script>
The script tag takes two important attributes:
⮚ Language: This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.
⮚ Type: This attribute is what is now recommended to indicate the scripting language in use and
its value should be set to "text/javascript".
Sample program in JavaScript:

Script place in <body> ..</body> section:


<html>
<body>
<script language="javascript" type="text/javascript">
document.write ("<h2 align=”center”>Welcome to JavascriptProgramming !</h2>")
</script>
</body>
</html>
Note: to print the messages on the screen we use a method known as document.write(“message”)
Obtaining user with prompt dialogs:
Prompt: The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label
which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. 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.
Syntax: prompt(“string”, “string”);

Page 2
MCA II Sem UNIT-2

Example: Write a program to perform arithmetic operations using JavaScript with prompt dialog
box?
<html>
<body>
<script type="text/javascript">
var a,b,result;
a = prompt("Enter first Number:");
b = prompt("Enter Second Number:");
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>

Page 3
MCA II Sem UNIT-2

What is Function? Explain different types of function in javascript.


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. It helps programmers in writing modular
codes. Functions allow a programmer to divide a big program into a number of small and manageable
functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions like alert() and write().
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of parameters
(that might be empty), and a statement block surrounded by curly braces.
Syntax: <script type="text/javascript">
function functionname(parameter-list)
{
Statements;
}
</script>
Functions are divided into two types:
1. Pre-defined functions
2. User-defined functions
Pre-defined function: The functions which already existed or default in JavaScript is called Pre-defined
function. These functions are like: write(), alert(), to uppercase(), to lower case(),date(), get date(), get
month().
User-defined function: These functions which are creating by the user is called User-defined function.
Syntax:
function functionname(parameter-list)
{
Statements;
}
Example: function sum()
{
var a,b,c;
a= prompt(“enter a value”);
b= prompt(“enter b value”);
c=a+b;
document.write(c);
}
Example: Calling a Function in html webpage
<html>
<head>

Page 4
MCA II Sem UNIT-2

<script type="text/javascript">
Function sayHello(name, age){
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('yakshita',3 )" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
</html>
Program Modules in javascript:
In JavaScript, program modules help in organizing code into separate, reusable blocks. Modules
improve code reusability, maintainability, and readability. They allow developers to break a large
program into smaller, manageable pieces.
Types of Program Modules in JavaScript
(i) Functions as Modules: Functions are the simplest way to create modules in JavaScript. A function
encapsulates a block of reusable code.
(ii) Objects as Modules: Objects in JavaScript can group related functions and variables together.
(iii)JavaScript Modules (ES6 Modules):JavaScript ES6 introduced the export and import keywords to
create modules.
(iv) Immediately Invoked Function Expressions (IIFE): An IIFE is a function that runs immediately
after being defined, acting as a module.
Advantages of Using Modules in JavaScript:
✔ Code Reusability – Modules allow functions to be reused in multiple programs.
✔ Encapsulation – Modules keep variables and functions separate from the global scope.
✔ Better Maintainability – Changes in one module do not affect the entire program.
✔ Improved Performance – Modular code is easier to debug and optimize.
<?xml version =”1.0”?>

<DOCTYPE html PUBLIC “-//W3C XHTML 1.0 Strict//En”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmls= “http://www.w3.org/1999/xhtml” >

<head>

Page 5
MCA II Sem UNIT-2

<title>JavaScript Program Modules</title>


<script type="text/javascript">
// Function as a module
function addNumbers(a, b) {
return a + b;
}
// Object as a module
var MathModule = {
multiply: function(a, b) {
return a * b;
},
divide: function(a, b) {
return a / b;
}
};

// Immediately Invoked Function Expression (IIFE)


(function() {
var message = "Welcome to JavaScript Modules!";
document.getElementById("message").innerHTML = message;
})();
</script>
</head>
<body>
<h1>JavaScript Program Modules</h1>
<p id="message"></p>
<h2>Function Module Example</h2>
<p>Sum of 5 and 3: <script type="text/javascript">document.write(addNumbers(5, 3));</script></p>
<h2>Object Module Example</h2>
<p>Multiplication of 4 and 2: <script type="text/javascript">document.write(MathModule.multiply(4,
2));</script></p>
<p>Division of 10 by 2: <script type="text/javascript">document.write(MathModule.divide(10,
2));</script></p>
</body>
</html>
Output:
JavaScript Program Modules

Page 6
MCA II Sem UNIT-2

Welcome to JavaScript Modules!


Function Module Example
Sum of 5 and 3: 8
Object Module Example
Multiplication of 4 and 2: 8
Division of 10 by 2: 5

Programmer-Defined Functions:
In JavaScript, functions are blocks of reusable code designed to perform a specific task. Programmer-
defined functions are custom functions created by developers to improve code efficiency and
maintainability.

What is a Programmer-Defined Function?


A programmer-defined function is a function that is explicitly created by the user, rather than being built
into JavaScript. These functions help in structuring code, avoiding repetition, and improving readability.
Syntax of a Programmer-Defined Function:
function functionName(parameters) {
// Function body (code to execute)
return result; // Optional return statement
}
● functionName → The name of the function.
● parameters → Input values (optional).
● return → Returns a value (optional).
Types of Programmer-Defined Functions in JavaScript:
1.Function Without Parameters and Without Return Value : These functions execute a task but do not
return any result.
2.Function With Parameters and Without Return Value:These functions take input values (arguments)
but do not return any result.
3.Function With Parameters and With Return Value:These functions take input values, process them,
and return a result.
4.Function Without Parameters and With Return Value:These functions do not take input values but
return a result.
Function Expressions:A function can also be assigned to a variable.
Arrow Functions (ES6 Feature):Arrow functions provide a shorter syntax for defining functions.
Benefits of Programmer-Defined Functions:
● Code Reusability → Functions reduce redundancy by reusing code.
● Modularity → Complex programs can be divided into smaller, manageable functions.
● Readability & Maintainability → Clean and structured code is easier to read and modify.
● Performance Optimization → Functions help in executing tasks efficiently.
Example:

Page 7
MCA II Sem UNIT-2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml ">
<head>
<title>JavaScript Functions in XHTML</title>
<script type="text/javascript">
// Function without parameters and without return value
function greet() {
alert("Hello, welcome to JavaScript functions!");
}
// Function with parameters and without return value
function greetUser(name) {
alert("Hello, " + name + "!");
}
// Function with parameters and with return value
function addNumbers(a, b) {
return a + b;
}
// Function without parameters and with return value
function getCurrentYear() {
return new Date().getFullYear();
}
</script>
</head>
<body>
<h1>JavaScript Functions in XHTML</h1>
<!-- Button to call function without parameters -->
<button onclick="greet()">Click to Greet</button>
<!-- Button to call function with parameter -->
<button onclick="greetUser('Pavan')">Click to Greet User</button>
<!-- Button to show sum of two numbers -->
<button onclick="alert('Sum: ' + addNumbers(10, 5))">Click to Add Numbers</button>
<!-- Button to display current year -->
<button onclick="alert('Current Year: ' + getCurrentYear())">Click to Get Year</button>
</body>
</html>

Page 8
MCA II Sem UNIT-2

Output:

Random number generation :-


Random number generation is essential in JavaScript for applications such as gaming, simulations,
cryptography, and dynamic content creation. JavaScript provides built-in methods to generate random
numbers using the Math object.Random number generation is a fundamental aspect of programming,
especially in web development, gaming, security, simulations, and artificial intelligence. JavaScript
provides built-in methods for generating random numbers, which are useful in various scenarios such as:
● Game Development – Randomly selecting items, generating dice rolls, or spawning objects.
● Data Simulation – Creating test data for applications.
● Cryptography – Generating random tokens for authentication.
● User Experience – Implementing dynamic themes or backgrounds.
JavaScript provides the Math.random() method to generate random numbers. However, since it
produces pseudo-random numbers, it is not suitable for cryptographic purposes.
Generating Random Numbers using Math.random():
JavaScript provides the Math.random() function, which generates a pseudo-random floating-point
number between 0 (inclusive) and 1 (exclusive).
Syntax: Math.random();
Generating Random Integers
To generate a random integer within a specific range, we modify Math.random().
Formula to Generate Random Integer in a Range:
Math.floor(Math.random() * (max - min + 1)) + min;
● Math.random() * (max - min + 1): Scales the random number to the required range.
● Math.floor(): Rounds down to the nearest integer.
● min: Ensures the number starts from the lower limit.
Applications:
● User Authentication: Generating random OTPs and passwords.
● Gaming: Randomizing character movements, attacks, and items.
● Data Sampling: Selecting random samples for statistical analysis.
● Web Development: Creating dynamic content like changing themes or random quotes.
Conclusion:
● Math.random() generates random floating-point numbers.
● Math.floor() converts floating-point numbers into integers.
● Custom functions help generate numbers in specific ranges.
● XHTML implementation ensures compatibility with structured web pages.
Program :-
<?xml version="2.0"?>
<!DOCTYPE html >
<html>
<head>
<title>Randam number Generation Ex</title>

Page 9
MCA II Sem UNIT-2

<script>
var num;
document.writeln("<table border=\"1\" width=\"50%\">");
document.writeln("<caption> Randam Numbers</caption><tr>");
for(var i=1; i<=20; i++)
{
num=Math.floor(1+Math.random()*6);
document.writeln("<td>" + num + "</td>");
if(i%5 ==0&& i!=20)
document.writeln("</tr><tr>");
}
</script>
</head>
<body>
<p> click refresh to run the script again</p>
</body>
</html>
Output:

Recursion Function:
● Recursion is a programming technique that allows the programmer to express operations in
terms of themselves.
● Recursion is a special way of nesting functions, where a function calls itself inside it. We must
have certain conditions in the function to break out of the recursion, otherwise recursion will
occur infinite times.
Advantages:
● Reduce unnecessary calling of function.
● Through Recursion one can solve problems in easy way while its iterative solution is very big
and complex.
Disadvantages:
● Recursive solution is always logical and it is very difficult to trace.(debug and understand).
● In recursive we must have an if statement somewhere to force the function to return without the
recursive call being executed, otherwise the function will never return.
● Recursion takes a lot of stack space, usually not considerable when the program is small and
running on a PC.
● Recursion uses more processor time.

What is an Array? Explain declaration of arrays in JavaScript.

Page 10
MCA II Sem UNIT-2

The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
⇨ Each value of the array is identified using its index value. Always first index of array will begin
with ‘0’ is known as “lower bound” of the array last index is identified by using “size-1” of the
array.
⇨ In JavaScript there are no predefined data types so within the array we can store any kind of
values. To create an array in JavaScript we use “array” keyword.
Syntax: datatype arrayname = new array(size/initializing elements)
Example:
1) var days = [ “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Satday”]
2) var A = new Array(6);
Array(6): means A[0]=20; A[1]=30; A[2]=40; A[3]=50; A[4]=60; A[5]=60;
3) A = new array(20,30,40,50,60,60);
Array Properties:
⮚ Construcctor: Returns a reference to the array function that created the object .
⮚ Index: The property represent the zero based index of the match in the string
⮚ Input : This property is only present in arrays created by regular expression matches.
⮚ Length: Reflects the number of elements in an array.
⮚ Prototype: the prototype property allows you to add properties and methods to an objects.
Example: To create an array and print length of array on the screen to the user.
<html>
<head>
<title>JavaScript Array length Property</title>
</head>
<body>
<script type="text/javascript">
Var arr = new Array( 10, 20, 30 );
document.write("arr.length is:" + arr.length);
</script>
</body>
</html>
ArrayMethods:
⮚ Concat(): Returns a new array comprised of this array joined with other array and or value
⮚ Every(): returns true if every element in this array satisfies the provided testing function.
⮚ Filter(): create a new array with all of the elements of this array for which the provided filtering
function returns true.
⮚ forEach(): Call a function for each element in the array

Page 11
MCA II Sem UNIT-2

⮚ Indexof(): Returns the first index of an element within the array equal to the specified value or 1
if none is found.
⮚ Join(): Joins all elements of an array into a string
⮚ lastIndexOf(): Returns the last Index of an element within the array equal to the specified value
or 1 if none is found
⮚ Map(): creates a new array with the results of calling a provided function on every element in
this array.
⮚ Pop(): Removes the last element from an array and returns that element.
Sorting arrays:-

Sorting data ( putting data in some particular order, such as or descending ) is one of the most important
computing functions. A bank sorts all checks by account number so that it can prepare individual bank
statements at the end of each mounth. Telephone companies sort their lists of accounts by last name and,
within that,by first name,to make it easy to find phone numbers. Virtually every organization must sort
some data-in many cases, massive amounts of data.

The array object in javascript has a built-in method sort for sorting arrays

Program:-

<?xml version =”1.0”?>

<DOCTYPE html PUBLIC “-//W3C XHTML 1.0 Strict//En”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmls= “http://www.w3.org/1999/xhtml” >

<head>

<title> Sorting and Array with Array Method sort</title>

<script type= “text/Javascript” >

function start()

var a=[10,1,9,2,8,3,7,4,6,5];

document.writeln("<h1>Sorting an Array</h1>");

outputArray("Data Items in original order",a);

a.sort(compareIntegers);

outputArray("Data items in ascending order:",a);

function outputArray(header,theArray)

Page 12
MCA II Sem UNIT-2

document.writeln("<p>" +header+ theArray.join(" ")+"</p>");

function compareIntegers(value1, value2)

return parseInt(value1)-parseInt(value2);

</script>

</head>

<body onload="start()">

</body>

</html>

Output:

Sorting an Array

Data items in original order: 10 1 9 2 8 3 7 4 6 5

Data items in ascending order: 1 2 3 4 5 6 7 8 9 10

Searching arrays:Linear search and Binary search:-

It may be necessary to determine whether an array contains a value that matches a certain key value the
process of locating a particular element value in an array is called searching, in this section we discuss
two searching techniques-the simple linear search technique and more efficient binary search.

1.Linear Search - Simple but slower for large datasets.

2.Binary Search - Faster but requires a sorted array.

Searching an array with Linear search

In the script in function linearsearch uses a for statement containing an if statement to compare each
element of an array with a search key. If the search key is found, the function returns the subscript value
of the element to indicate the exact position of the search key in the array.if the search key is not found,
the function returns a value of -1. The function returns the value -1 because it is not a valid subscript
number.

Program:-

Page 13
MCA II Sem UNIT-2

<?xml version =”1.0”?>

<DOCTYPE html PUBLIC “-//W3C XHTML 1.0 Strict//En”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >

<html xmls= “http://www.w3.org/1999/xhtml ” >

<head>

<title>Linear Search</title>

<script type="text/javascript">

function linearSearch() {

var arr = [5, 8, 12, 15, 20];

var target = parseInt(document.getElementById("linearInput").value);

var result = -1;

for (var i = 0; i < arr.length; i++) {

if (arr[i] === target) {

result = i;

break;

document.getElementById("linearResult").innerHTML =

result !== -1 ? "Element found at index " + result : "Element not found";

</script>

</head>

<body>

<h2>Linear Search</h2>

<p>Enter a number to search: <input type="text" id="linearInput" /></p>

<button onclick="linearSearch()">Search</button>

<p id="linearResult"></p>

</body>

Page 14
MCA II Sem UNIT-2

</html>

Output1:

linearSearch

Enter integer to search

| 12 ||Search|

Element found at index 2

Output2:

linearSearch

Enter integer to search

| 10 ||Search|

Element not found

Searching an array with Binary search

The linear-search method works well for small arrays or for unsorted arrays. However, for large arrays,
linear searching is inefficient. If the array is sorted, the high-speed binary search technique can be used.
After each comparison, the binary search algorithm eliminates half of the elements in the array being
searched. The algorithm locates the middle array element and compares it to the search key. If they are
equal, the search key has been found and the subscript of that element is returned. Otherwise ,the
problem is reduced to searching half of the array. If the search key is less than the middle array element,
the first half of the array is searched; otherwise, the second half of the array is searched. If the search
key is not the middle element in the specified subarray ( piece of the original array ), the algorithm is
repeated on one quarter of the original array. The search continues until the search key is equal to the
middle element of a subarray or until the subarray consists of one element that is not equal to the search
key.

In a worst-case scenario, searching an array of 1023 elements will take only 10 comparisons using a
binary search.

Program:-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>Binary Search</title>

<script type="text/javascript">

Page 15
MCA II Sem UNIT-2

function binarySearch() {

var arr = [3, 7, 10, 14, 18, 22]; // Sorted Array

var target = parseInt(document.getElementById("binaryInput").value);

var low = 0, high = arr.length - 1;

var result = -1;

while (low <= high) {

var mid = Math.floor((low + high) / 2);

if (arr[mid] === target) {

result = mid;

break;

} else if (arr[mid] < target) {

low = mid + 1;

} else {

high = mid - 1;

document.getElementById("binaryResult").innerHTML =

result !== -1 ? "Element found at index " + result : "Element not found";

</script>

</head>

<body>

<h2>Binary Search</h2>

<p>Enter a number to search: <input type="text" id="binaryInput" /></p>

<button onclick="binarySearch()">Search</button>

<p id="binaryResult"></p>

</body>

Page 16
MCA II Sem UNIT-2

</html>

Output:

Binary Search

Enter number to search:

| 14 ||search|

Element found at index 3

What is an Objects?
An object is a thing. It can be anything that you like from some data through a set of methods to an
entire system. Objects are described in software and design constructs called classes. A class usually
contains some data items and some methods. Each class provides services to other classes in the system.
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 related information, whether data or methods, together in
an object.
● Aggregation: the capability to store one object inside another object.
● Inheritance: the capability of a class to rely upon 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 are composed of attributes. If an attribute contains a function, it is considered to be a method of
the object; otherwise the attribute is considered a property.
Object properties:
Object properties can be any of the three primitive data types, or any of the abstract data types, such as
another object. Object properties are usually variables that are used internally in the object's methods,
but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
Example:var str = document.title;
Object Method:
Methods are the functions that let the object do something or let something be done to it. There is a
small difference between a function and a method – at a function is a standalone unit of statements and a
method is attached to an object and can be referenced by the this keyword.
For example: Following is a simple example to show how to use the write() method of document object
to write any content on the document.
document.write ("This is test");
User-defined objects:
All user-defined objects and built-in objects are descendants of an object called Object.
The new operator:

Page 17
MCA II Sem UNIT-2

The new operator is used to create an instance of an object. To create an object, the new operator
is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors
are built-in JavaScript functions.
Example: var employee = new Object();
var books = new Array("C++", "c", "Java");
This: To differentiate between global variable and those which are part of an object but may have the
same name, JavaScript uses this. Whenever you refer to a variable which is part of an object you must
precede the variable name by this. Separate the variable name from this with a dot.
.(dot):When referring to a property of an object, whether a method or a variable, a dot is placed between
name and the property.
Example: it shows how to add a function along with an object. Defining methods for an object
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
Function addPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
Var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Boolean And number objects:

Page 18
MCA II Sem UNIT-2

Javascrit provides the Boolean and number objects as object wrappers for Boolean true/flase values and
numbers, respectively.these wrappers define methods and properties useful in manipulating Boolean
values and numbers.
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is
0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Syntax: Use the following syntax to create a Boolean object.
Var b = new Boolean( boolean value);
Boolean Method:

Page 19

You might also like