UNIT-2
UNIT-2
INTRODUCTION TO JAVASCRIPT:
WHAT IS JAVASCRIPT?
HTML and CSS concentrate on a static rendering of a page; things do not change on the
page over
time, or because of events.
To do these things, we use scripting languages, which allow content to change
dynamically.
Not only this, but it is possible to interact with the user beyond what is possible with
HTML.
Scripts are programs just like any other programming language; they can execute on the
client side or the server.
JavaScript is a high-level, dynamic, multi-paradigm programming language that is
primarily used for creating interactive web applications.
It was created by Brendan Eich at Netscape Communications in 1995 and has since
become one of the most widely used programming languages in the world.
JavaScript is a client-side scripting language, which means that it is executed by the web
browser on the client-side (i.e., on the user's computer).
This allows for dynamic and interactive web pages that can respond to user input and
update content without the need for a page reload.
Some common uses for JavaScript include form validation, creating dynamic HTML
content, creating interactive animations, and adding interactivity to web-based games.
It can also be used on the server-side with technologies like Node.js.
JavaScript is a versatile language that can be used in a variety of different ways, from
small scripts on a single web page to complex applications with thousands of lines of
code.
It is supported by all major web browsers and has a large community of developers who
contribute to a wide range of libraries, frameworks, and tools.
<body>
<script type="text/JavaScript">
<!--
var two = 2
var ten = 10
varlinebreak = "<br />"
document.write("two plus ten = ")
var result = two + ten
document.write(result)
//-->
</script>
</body>
THE DATE OBJECT
JavaScript provides the Date object for manipulating date and time. Like the String and
Array objects, you can create as many instances as you like.
EXAMPLE
var Date = new Date(); // The new constructor returns a Date object.
var Date = new Date("July 4, 2004, 6:25:22");
var Date = new Date("July 4, 2004");
var Date = new Date(2004, 7, 4, 6, 25, 22);
var Date = new Date(2004, 7, 4);
var Date = new Date(Milliseconds);
Using the Date Object Methods
Method What It Does
getDate Returns the day of the month (1–31)
getDay Returns the day of the week (0–6); 0 is Sunday, 1 is Monday, etc.
getFullYear Returns the year with 4 digits
getHours Returns the hour (0–23)
getMilliseconds Returns the millisecond
getMinutes Returns hours since midnight (0–23)
getMonth Returns number of month (0–11); 0 is January, 1 is February, etc.
getSeconds Returns the second (0–59)
setDate(value) Sets day of the month (1–31)
setFullYear() Sets the year as a four-digit number
setHours() Sets the hour within the day (0–23)
setHours(hr,min,sec,msec) Sets hour in local
setMilliseconds Sets the millisecond
setMinutes(min,sec, msec) Sets minute in local time
setMonth(month,date) Sets month in local time
setSeconds() Sets the second
setTime() Sets time from January 1, 1970, in milliseconds
setYear() Sets the number of years since 1900 (00–99)
toGMTString() Returns the date string in universal format
toString Returns string representing date and time
valueOf() Returns the equivalence of the Date object in milliseconds
EXAMPLE
<html>
<head><title>Time and Date</title></head>
<body bgcolor="lightblue"><h2>Date and Time</h2>
<script language="JavaScript">
var now = new Date(); // Now is an instance of a Date object
document.write("<font size='+1'>");
document.write("<b>Local time:</b> " + now + "<br>");
var hours=now.getHours();
var minutes=now.getMinutes();
var seconds=now.getSeconds();
var year=now.getFullYear();
document.write("The full year is " + year +"<br>");
document.write("<b>The time is:</b> " +
hours + ":" + minutes + ":" + seconds);
document.write("</font>");
</script>
</body>
</html>
EXAMPLE
<html>
<head>
<title>Using the JavaScript confirm box</title>
</head>
<body>
<script language = "JavaScript">
document.clear // Clears the page
if(confirm("Are you really OK?") == true){
alert("Then we can proceed!");
}
else{
alert("We'll try when you feel better? ");
}
</script>
</body>
</html>
Here's an example:
// var z = 20; // This line of code is commented out
var z = 30; // This line of code will be executed
In this example, the first line of code is commented out, which means it will be ignored by the
browser. The second line of code will be executed and the variable z will be assigned the value
of 30.
PRIMITIVES OPERATIONS AND EXPRESSIONS:
In JavaScript, primitives are basic data types that can represent simple values. There are six
primitive types in JavaScript:
1. Boolean: represents a logical value of true or false.
2. Null: represents a value that is intentionally empty or non-existent.
3. Undefined: represents a value that has not been assigned a value.
4. Number: represents a numeric value, including integers and floating-point numbers.
5. String: represents a sequence of characters.
6. Symbol: represents a unique value that can be used as an identifier for object properties.
Primitive operations in JavaScript involve performing operations on primitive values. Some of
the primitive operations include:
1. Arithmetic Operators: These are used to perform mathematical operations on number
values. The arithmetic operators include addition (+), subtraction (-), multiplication (*), division
(/), and modulus (%).
2. Comparison Operators: These are used to compare values and return a Boolean value of
true or false. The comparison operators include equality (==), inequality (!=), strict equality
(===), strict inequality (!==), greater than (>), less than (<), greater than or equal to (>=), and
less than or equal to (<=).
3. Logical Operators: These are used to perform logical operations on Boolean values. The
logical operators include logical AND (&&), logical OR (||), and logical NOT (!).
4. Assignment Operators: These are used to assign values to variables. The assignment
operators include =, +=, -=, *=, /=, and %=.
Expressions in JavaScript are combinations of operators, variables, and values that evaluate to a
single value. For example, the expression 2 + 3 evaluates to the value 5. Expressions can be
simple, such as a single value or variable, or they can be complex, involving multiple operators
and values. Some examples of expressions in JavaScript include:
1. 2+3
2. "Hello, " + "world!"
3. (2 * 3) + (4 / 2)
4. x=5
5. y += 10
Overall, primitives, operations, and expressions are fundamental concepts in JavaScript that are
used extensively in programming.
Expressions in JavaScript are any valid unit of code that evaluates to a value. Here are some
examples of expressions in JavaScript:
1. Arithmetic expressions: These are expressions that involve mathematical operators and
evaluate to a numeric value. For example:
2 + 3 // evaluates to 5
4 * 5 // evaluates to 20
10 - 6 // evaluates to 4
2. String expressions: These are expressions that involve string literals and string operators,
and evaluate to a string value. For example:
'Hello ' + 'world' // evaluates to 'Hello world'
'2' + '3' // evaluates to '23'
3. Boolean expressions: These are expressions that evaluate to a boolean value (true or
false) based on some logical condition. For example:
4 < 5 // evaluates to true
2 === '2' // evaluates to false
4. Function expressions: These are expressions that involve defining a function and
evaluating it. For example:
let square = function(num) {
return num * num;
}
square(5) // evaluates to 25
5. Object expressions: These are expressions that define and evaluate an object. For
example:
let person = {
name: 'John',
age: 30,
isStudent: true
};
4. Object.assign(): The Object.assign() method is used to copy the values of all enumerable
properties from one or more source objects to a target object.
const person1 = {
name: 'John',
age: 30
};
const person2 = {
address: 'New York'
};
delete person1.address;
MODIFICATION OF OBJECTS:
In JavaScript, objects are mutable, which means you can modify their properties and methods
after they are created. Here are some ways to modify an object in JavaScript:
1. Dot notation: You can modify an object's property using dot notation by specifying the
property name after the object name, and assigning a new value to it.
const person = {
name: 'John',
age: 30
};
person.age = 35;
2. Bracket notation: You can also modify an object's property using bracket notation by
specifying the property name inside square brackets and assigning a new value to it.
const person = {
name: 'John',
age: 30
};
person['age'] = 35;
3. Adding new properties: You can add new properties to an object by specifying a new
property name and value using either dot notation or bracket notation.
const person = {
name: 'John',
age: 30
};
4. Deleting properties: You can delete a property from an object using the delete operator.
const person = {
name: 'John',
age: 30,
city: 'New York'
};
delete person.city;
5. Object.assign(): You can use the Object.assign() method to merge two or more objects into a
single object, which can also be used to modify an existing object.
const person = {
name: 'John',
age: 30
};
const additionalInfo = {
city: 'New York',
occupation: 'Developer'
};
Object.assign(person, additionalInfo);
In the above example, person object is modified to include the properties city and occupation
from the additionalInfo object.
JAVASCRIPT ARRAY
An array is a special variable, which can hold more than one value at a time.
The Array object is used to store multiple values in a single variable.
An array can be created in three ways.
The following code creates an Array object called myCars.
1. Regular
varmyCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2. Condensed
varmyCars=new Array("Saab","Volvo","BMW");
3. Literal
Access an Array
You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars.
var name=myCars[0];
This statement modifies the first element in myCars:
myCars[0]="Opel";
JAVASCRIPT FUNCTIONS
A function is a section of code that is separate from the main program.
It is defined once but can be invoked many times.
A function can be passed as parameters so that they can be used and a value can be returned
back.
There are some functions already built in to JavaScript, such as the Math.cos() function, which
calculates the cosine of an angle.
An example function could be:
functionmultByTen(x)
{
return x*10;
}
This can then be invoked by using the function’s name complete with any parameters you want
to
pass:
mysum=multByTen(3)
Below is an example of JavaScript function.
<html><body>
<script type=”text/javascript”>
var z= multXbyY(10,15);
document.write(“The result is” +z);
functionmultXbyY(x,y) {
document.write(“x is ” +x);
document.write(“y is ”+y);
return x*y;
}
</script>
</body>
</html>
Functions are a fundamental part of JavaScript, which is a functional programming language.
A function is a block of code that can be invoked or called to perform a specific task or set of
tasks.
In JavaScript, functions are objects, which means they can be assigned to variables, passed as
arguments to other functions, or even returned as values from other functions.
Here's an overview of how to define and use functions in JavaScript:
Function Declaration
The most common way to define a function is using a function declaration, which uses the
function keyword, followed by the function name, a set of parentheses that may include one or
more parameters, and a set of curly braces that enclose the function body.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('John');
Function Expression
You can also define a function using a function expression, which assigns an anonymous
function to a variable.
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
greet('John');
Arrow Function
Arrow functions are a more concise way of writing function expressions, which use the =>
syntax instead of the function keyword.
const greet = (name) => {
console.log(`Hello, ${name}!`);
};
greet('John');
Default Parameters
You can set default values for function parameters using the = operator.
function greet(name = 'World') {
console.log(`Hello, ${name}!`);
}
greet();
Rest Parameters
You can use the rest parameter syntax (...) to represent an indefinite number of arguments as an
array.
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
sum(1, 2, 3, 4); // returns 10
Callback Functions
A callback function is a function that is passed as an argument to another function and is called
when the main function has completed its task.
function doSomething(callback) {
// perform some task
callback();
}
These are some of the basic concepts of functions in JavaScript. Functions are a powerful feature
in JavaScript and can be used to create reusable code, implement complex algorithms, and build
sophisticated applications.
CONSTRUCTORS:
In JavaScript, a constructor is a function that is used to create and initialize objects.
Constructors are used to create new instances of a particular type of object, and they define the
initial state and behavior of that object.
To create a constructor function in JavaScript, you can use the function keyword followed by the
name of the constructor.
The convention is to capitalize the first letter of the constructor name. Inside the constructor
function, you can use the this keyword to refer to the object that is being created, and you can
add properties and methods to the object using dot notation.
Here is an example of a simple constructor function that creates objects representing cars:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.start = function() {
console.log("Starting the " + this.make + " " + this.model);
};
}
In this example, the Car constructor takes three parameters (make, model, and year) and assigns
them to properties of the object using this. It also defines a method called start that logs a
message to the console.
To create a new instance of a Car object using the Car constructor, you can use the new keyword
followed by the name of the constructor, passing in the appropriate arguments:
var myCar = new Car("Toyota", "Camry", 2018);
This creates a new Car object with the specified properties and assigns it to the variable myCar.
You can then call methods on the myCar object, such as:
myCar.start(); // logs "Starting the Toyota Camry"
Note that constructors in JavaScript can also inherit from other constructors using the prototype
property, and they can be called using the call or apply methods to set the this value explicitly.
PATTERN MATCHING USING REGULAR EXPRESSIONS DHTML:
Pattern matching using regular expressions in DHTML (Dynamic HTML) involves using regular
expression syntax to search for patterns in strings or text content of HTML elements.
This can be useful for validating user input in forms, searching and replacing text, or extracting
specific information from a string.
To use regular expressions in DHTML, you can use the RegExp object, which represents a
regular expression pattern.
You can create a new RegExp object by passing a regular expression pattern as a string to the
constructor, like this:
var pattern = new RegExp("hello");
This creates a regular expression pattern that matches the string "hello". You can also create
regular expression patterns using literal notation, like this:
var pattern = /hello/;
Once you have created a regular expression pattern, you can use it to search for matches in a
string using the test method, which returns true if the pattern matches the string, or false
otherwise:
var result = pattern.test("hello world");
In this example, the test method returns true because the pattern matches the string "hello world".
You can also use the match method of a string object to search for matches of a regular
expression pattern and return an array of matches:
var str = "The quick brown fox";
var pattern = /q[a-z]+/;
var matches = str.match(pattern);
In this example, the regular expression pattern /q[a-z]+/ matches the string "quick", so the match
method returns an array containing the string "quick".
Regular expression patterns can be more complex than simple string literals, allowing you to
match specific patterns of characters or groups of characters. Some common regular expression
syntax includes:
Regular expressions can also include special characters, called metacharacters, that have special
meanings. To match a metacharacter as a literal character, you need to escape it with a backslash
().
Regular expressions can be a powerful tool for working with text content in DHTML, but they
can also be complex and require careful testing and debugging.
DHTML:
Dynamic HTML, or DHTML, is for a collection of technologies used together to create
interactive and animated by using a combination of a static markup language (such as
HTML), a client-side scripting language (such as JavaScript), a presentation definition
language (such as CSS), and the Document Object Model.
DHTML allows scripting languages to change variables in a web page's definition
language, which in turn affects the look and function of otherwise "static" HTML page
content, after the page has been fully loaded and during the viewing process.
Thus the dynamic characteristic of DHTML is the way it functions while a page is viewed, not in
its ability to generate a unique page with each page load.
By contrast, a dynamic web page is a broader concept — any web page generated
differently for each user, load occurrence, or specific variable values.
This includes pages created by client-side scripting, and ones created by server-side scripting
(such as PHP, Perl, JSP or ASP.NET) where the web server generates content before sending it
to the client. Uses DHTML allows authors to add effects to their pages that are otherwise
difficult to achieve. For example, DHTML allows the page author to:
Animate text and images in their document, independently moving each element
from any starting point to any ending point, following a predetermined path or one
chosen by the user.
Embed a ticker that automatically refreshes its content with the latest news, stock
quotes, or other data.
Use a form to capture user input, and then process and respond to that data without
having to send data back to the server.
Include rollover buttons or drop-down menus.
DHTML FORMS
Forms are key components of all Web-based applications. But important as they
are, Web developers often present users with forms that are difficult to use. There
are three common problems:
Forms can be too long. A seemingly endless list of questions is sure to make the
user click the back button or jump to another site.
In many situations a specific user will need to fill out only some of the form
elements. If you present needless questions to a user, you’ll add clutter to your
page and encourage the user to go elsewhere.
Form entries often need to conform to certain formats and instructions. Adding
this information to a Web page can make for a cluttered and unappealing screen.
Choosing The Form You Want
A long form can be shortened in a number of ways. If you have multiple versions of a
form, the chief task becomes pointing people to the right form. Often, a simple set of
links will do: “click here for the simple form, click here for the more complicated one.”
Alternatively, a single page can show one of several forms that the visitor can choose
between using radio buttons.
This approach uses Dynamic HTML (DHTML), which has several benefits. First,
DHTML allows for more flexible formatting. You can apply background images, borders,
fonts, and all the other features you’ve learned to expect from HTML and Cascading
Style Sheets to
DHTML objects. Second, if someone fills out one form, switches to another, then
switches back, there’s a good chance that the browser will lose the information that was
initially entered. This problem doesn’t exist in the DHTML solution. Third, with DHTML
you can do tricky things like clipping and moving the form around the page.
POSITIONING MOVING AND CHANGING ELEMENTS:
Pattern matching using regular expressions (regex) is a powerful technique for working with text
data in JavaScript. In addition to manipulating strings, regular expressions can be used in a
variety of applications, such as form validation, search and replace, and parsing data.
In the context of DHTML (Dynamic HTML), regular expressions can be used to manipulate
elements on a web page, such as positioning, moving, and changing their content. Here are a few
examples of how regular expressions can be used for DHTML:
Positioning elements
Regular expressions can be used to set the position of an element relative to its parent or to the
browser window. For example, the following code sets the position of a div element with the ID
"myDiv" to the center of the browser window:
var myDiv = document.getElementById("myDiv");
myDiv.style.position = "absolute";
myDiv.style.left = (window.innerWidth / 2 - myDiv.offsetWidth / 2) + "px";
myDiv.style.top = (window.innerHeight / 2 - myDiv.offsetHeight / 2) + "px";
Moving elements
Regular expressions can be used to move elements on a web page, either in response to user
input or as part of an animation. For example, the following code moves a div element with the
ID "myDiv" to the right by 100 pixels when the user clicks on it:
var myDiv = document.getElementById("myDiv");
myDiv.onclick = function() {
var currentLeft = parseInt(myDiv.style.left);
myDiv.style.left = (currentLeft + 100) + "px";
};
Changing element content
Regular expressions can be used to change the content of an element on a web page, such as
updating the text of a heading or changing the source of an image. For example, the following
code changes the text of an h1 element with the ID "myHeading" to "Hello, World!":
var myHeading = document.getElementById("myHeading");
myHeading.innerHTML = "Hello, World!";
Regular expressions can also be used to search for and replace specific patterns of text within an
element's content, using methods like replace() and match(). For example, the following code
replaces all occurrences of the word "JavaScript" with "TypeScript" in the content of an element
with the ID "myText":
var myText = document.getElementById("myText");
myText.innerHTML = myText.innerHTML.replace(/JavaScript/g, "TypeScript");
In summary, regular expressions are a powerful tool for working with text data in JavaScript,
including manipulating elements on a web page in DHTML. By learning to use regular
expressions effectively, you can create dynamic and interactive web experiences that respond to
user input and update in real-time.