0% found this document useful (0 votes)
4 views43 pages

UNIT-2

This document provides an introduction to JavaScript, detailing its purpose as a dynamic, client-side scripting language for creating interactive web applications. It covers the advantages and disadvantages of client-side scripting, differentiates between client-side and server-side scripting, and compares JavaScript with Java. Additionally, it discusses JavaScript variables, operators, objects, dialog boxes, and the creation of static and dynamic web pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views43 pages

UNIT-2

This document provides an introduction to JavaScript, detailing its purpose as a dynamic, client-side scripting language for creating interactive web applications. It covers the advantages and disadvantages of client-side scripting, differentiates between client-side and server-side scripting, and compares JavaScript with Java. Additionally, it discusses JavaScript variables, operators, objects, dialog boxes, and the creation of static and dynamic web pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

UNIT-II

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.

ADVANTAGES OF CLIENT-SIDE SCRIPTING:


 The web browser uses its own resources, and eases the burden on the server.
 It has fewer features than server-side scripting.
 It saves network bandwidth.

DISADVANTAGES OF CLIENT-SIDE SCRIPTING:


 Code is usually visible.
 Code is probably modifiable.
 Local files and databases cannot be accessed.
 User is able to disable client-side scripting.

DIFFERENTIATE BETWEEN SERVER SIDE AND CLIENT-SIDE SCRIPTING


LANGUAGES
Client-side scripting languages
 The client-side environment used to run scripts is usually a browser.
 The processing takes place on the end users computer.
 The source code is transferred from the web server to the user’s computer over the
internet and run
 directly in the browser.
 The scripting language needs to be enabled on the client computer.
 Sometimes if a user is conscious of security risks they may switch the scripting facility
off.
 When this is the case a message usually pops up to alert the user when script is
attempting to run.
Server-side scripting languages
 The server-side environment that runs a scripting language is a web server.
 A user's request is fulfilled by running a script directly on the web server to generate
dynamic HTML
 pages.
 This HTML is then sent to the client browser.
 It is usually used to provide interactive web sites that interface to databases or other data
stores on the server.
 This is different from client-side scripting where scripts are run by the viewing web
browser, usually in JavaScript.
 The primary advantage to server-side scripting is the ability to highly customize the
response based on the user's requirements, access rights, or queries into data stores.
WHAT IS DIFFERENCE BETWEEN JAVA SCRIPT AND JAVA?
 Java is a statically typed language; JavaScript is dynamic.
 Java is class-based; JavaScript is prototype-based.
 Java constructors are special functions that can only be called at object creation;
JavaScript
 "constructors" are just standard functions.
 Java requires all non-block statements to end with a semicolon; JavaScript inserts
semicolons at the ends of certain lines.
 Java uses block-based scoping; JavaScript uses function-based scoping.
 Java has an implicit this scope for non-static methods, and implicit class scope;
JavaScript has implicit global scope.
EXTERNAL JAVASCRIPT
 If you want to use the same script on several pages it could be a good idea to place the
code in a separate file, rather than writing it on each.
 That way if you want to update the code, or change it, you only need to do it once.
 Simply take the code you want in a separate file out of your program and save it with the
extension.js.
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
JAVASCRIPT VARIABLES
 Variables in JavaScript behave the same as variables in most popular programming
languages (C,
 C++, etc) do, but in JavaScript you don't have to declare variables before you use them.
 A variable's purpose is to store information so that it can be used later. A variable is a
symbolic name that represents some data that you set.
 When using a variable for the first time it is not necessary to use "var" before the variable
name.
 Variable names must begin with a letter.
 Variable names are case sensitive (y and Y are different variables).
 You can declare many variables in one statement. Just start the statement with var and
separate the variables by comma:
var name="Doe", age=30, job="carpenter";
var name="Doe",
age=30,
job="carpenter";
 Variable declared without a value will have the value undefined.
 If you re-declare a JavaScript variable, it will not lose its value.
 The value of the variable carname will still have the value "Volvo" after the execution of
the following two statements.
varcarname="Volvo";
varcarname;
JAVASCRIPT OPERATORS
 Operators in JavaScript are very similar to operators that appear in other programming
languages.
 The definition of an operator is a symbol that is used to perform an operation.
 Most often these operations are arithmetic (addition, subtraction, etc), but not always.

<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>

THE BOOLEAN OBJECT


The Boolean object was included in JavaScript 1.1. It is used to convert a non-Boolean
value to a Boolean value, either true or false. There is one property, the prototype
property, and one method, the toString() method, which converts a Boolean value to a
string; thus, true is converted to "true" and false is converted to "false".
var object = new Boolean(value);
EXAMPLE:
var b1 = new Boolean(5);
var b2 = new Boolean(null);
<html><head><title>Boolean Object</title>
</head>
<body bgcolor=aqua>
<font face="arial" size="+1"><b>
The Boolean Object<br>
<font size="-1">
<script language="JavaScript">
var bool1= new Boolean( 0);
var bool2 = new Boolean(1);
var bool3 = new Boolean("");
var bool4 = new Boolean(null);
var bool5 = new Boolean(NaN);
document.write("The value 0 is boolean "+ bool1 +"<br>");
document.write("The value 1 is boolean "+ bool2 +"<br>");
document.write("The value of the empty string is boolean "+ bool3+ "<br>");
document.write("The value of null is boolean "+ bool4+ "<br>");
document.write("The value of NaN is boolean "+ bool5 +"<br>");
</script>
</body>
</html>
POPUP BOXES:
JavaScript uses dialog boxes to interact with the user. The dialog boxes are created with
three methods:
 alert()
 prompt()
 confirm()
The alert() Method
<html>
<head><title>Dialog Box</title></head>
<body bgcolor="yellow" text="blue">
<b>Testing the alert method</b><br>
<script language="JavaScript">
document.write("<font size='+2'>");
document.write("It's a bird, ");
document.write("It's a plane, <br>");
alert("It's Superman!");
</script>
</body></html>
The Prompt Box
Since JavaScript does not provide a simple method for accepting user input, the prompt
dialog box and HTML forms are used. The prompt dialog box pops up with a simple text
field box. After the user enters text into the prompt dialog box, its value is returned.
FORMAT
prompt(message);
prompt(message, defaultText);
Example:
prompt("What is your name? ", "");
prompt("Where is your name? ", name);
The Confirm Box
The confirm dialog box is used to confirm a user's answer to a question. A question mark
will appear in the box with an OK button and a Cancel button. If the user presses the OK
button, true is returned; if he presses the Cancel button, false is returned. This method
takes only one argument, the question you will ask the user.

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>

Web pages are of two types.


1. Static web pages
2. Dynamic web pages
Static web pages:
A static web page is a web page that displays the same content to all users and does not change
unless it is manually updated.
In contrast, a dynamic web page is a web page that can change dynamically based on user
interactions or server-side processing.
To create a static web page with JavaScript, you can use it to manipulate the HTML and CSS
content of the page.
For example, you can use JavaScript to change the text or images on the page, add or remove
HTML elements, or modify the CSS styles that control the layout and appearance of the page.
Here is an example of a simple static web page that uses JavaScript to display a message:
<html>
<head>
<title>Static Web Page with JavaScript</title>
<script>
function showMessage() {
var message = "Hello, World!";
document.getElementById("message").innerHTML = message;
}
</script>
</head>
<body>
<h1>Static Web Page with JavaScript</h1>
<p id="message">Click the button to display a message.</p>
<button onclick="showMessage()">Show Message</button>
</body>
</html>
In this example, the JavaScript function showMessage() is defined in the <script> element in the
<head> section of the page. When the user clicks the "Show Message" button, the function is
called and sets the text of the <p> element with the ID "message" to "Hello, World!".
This is a simple example, but it demonstrates how JavaScript can be used to create static web
pages that are more interactive and engaging for users.
Dynamic web pages:
Dynamic web pages are web pages that can change dynamically based on user interactions,
database queries, or other server-side processing.
JavaScript is a key technology used to create dynamic web pages, as it allows for interactivity
and responsiveness in real-time.
Dynamic web pages typically use a combination of server-side programming languages (like
PHP, Ruby, or Python) and client-side technologies (like JavaScript and HTML) to deliver a
dynamic user experience.
The server-side language is used to generate dynamic content, while the client-side technologies
are used to update the content in real-time based on user interactions.
Here is an example of a dynamic web page that uses JavaScript to update the content based on
user interactions:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Web Page with JavaScript</title>
<script>
function calculateTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total = price * quantity;
document.getElementById("total").innerHTML = total;
}
</script>
</head>
<body>
<h1>Dynamic Web Page with JavaScript</h1>
<p>Price: $<input type="number" id="price" value="10"></p>
<p>Quantity: <input type="number" id="quantity" value="1"></p>
<button onclick="calculateTotal()">Calculate Total</button>
<p>Total: $<span id="total"></span></p>
</body>
</html>
In this example, the user inputs a price and quantity, and then clicks the "Calculate Total" button.
When the button is clicked, the JavaScript function calculateTotal() is called, which retrieves the
values of the price and quantity input fields, calculates the total, and updates the content of the
<span> element with the ID "total" to display the calculated total.
This is a simple example, but it demonstrates how JavaScript can be used to create dynamic web
pages that respond to user input in real-time. Other examples of dynamic web pages include real-
time chat applications, web-based games, and e-commerce websites that display product
recommendations based on user behavior.
COMMENTS IN JAVA SCRIPT:
In JavaScript, you can add comments to your code to provide explanations or notes that are
ignored by the browser when the code is executed. Comments are a useful tool for making your
code more readable and understandable to others who may be reading or modifying your code.
There are two types of comments in JavaScript:
1. Single-line comments: Single-line comments start with two forward slashes //. Anything
you write after the double slashes on the same line will be ignored by the browser.
Here's an example:
// This is a single-line comment
var x = 5; // You can also add a comment after a line of code
2. Multi-line comments: Multi-line comments start with a forward slash and asterisk /* and
end with an asterisk and forward slash */. Anything you write between the opening and closing
characters will be ignored by the browser.
Here's an example:
/*
This is a multi-line comment.
It can span multiple lines.
*/
var y = 10; /* You can also use multi-line comments for single lines of code */
Comments can also be used to temporarily disable a block of code without deleting it. This can
be useful for debugging or testing purposes.

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
};

person.name // evaluates to 'John'


person.isStudent // evaluates to true

SCREEN OUTPUT AND KEYBOARD INPUT:


In JavaScript, you can output text to the screen and take input from the keyboard using various
methods. Here are some commonly used methods for screen output and keyboard input in
JavaScript:
Screen Output:
1. console.log(): This method is used to output text to the console in the browser's developer
tools. It takes one or more arguments and displays them in the console. For example:
console.log('Hello, world!');
2. document.write(): This method is used to write text directly to the HTML document. It
takes one argument and writes it to the document. For example:
document.write('Hello, world!');
3. alert(): This method is used to display a message in a pop-up alert box. It takes one
argument and displays it in the alert box. For example:
alert('Hello, world!');
Keyboard Input:
1. prompt(): This method is used to display a message and prompt the user to enter a value
in a pop-up dialog box. It takes one argument (the message to display) and returns the value
entered by the user. For example:
let name = prompt('What is your name?');
console.log('Hello, ' + name + '!');
2. confirm(): This method is used to display a message and prompt the user to confirm or
cancel an action in a pop-up dialog box. It takes one argument (the message to display) and
returns a boolean value indicating whether the user confirmed or canceled the action. For
example:
let result = confirm('Are you sure you want to delete this item?');
if (result) {
// delete the item
} else {
// do nothing
}
Note that prompt() and confirm() are synchronous methods, which means that they block the
execution of the code until the user enters a value or confirms/cancels the action. Asynchronous
methods such as callbacks, promises, or async/await can also be used for input in modern
JavaScript.
JAVASCRIPT CONDITIONS
 Conditional statements are used to perform different actions based on different
conditions.
 In JavaScript we have the following conditional statements:
o if statement - use this statement to execute some code only if a specified condition is true
o if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
o if...else if....else statement - use this statement to select one of many blocks of code to be
executed
o switch statement - use this statement to select one of many blocks of code to be executed
In JavaScript, you can create and modify objects using a variety of techniques. Here are some
common approaches:
OBJECT CREATION AND MODIFICATION:
1. Object Literals: One of the simplest ways to create an object in JavaScript is by using
object literals. An object literal is a comma-separated list of name-value pairs enclosed in
curly braces.
const person = {
name: 'John',
age: 30,
address: {
city: 'New York',
state: 'NY',
country: 'USA'
}
};
2. Constructor Functions: Constructor functions are special functions that are used to create
new instances of objects. You can define a constructor function using the function
keyword and the this keyword to create properties and methods for the object.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Hello, my name is ' + this.name);
}
}

const person1 = new Person('John', 30);


3. Object.create(): The Object.create() method creates a new object with the specified
prototype object and properties.
const personPrototype = {
greet: function() {
console.log('Hello, my name is ' + this.name);
}
};

const person1 = Object.create(personPrototype);


person1.name = 'John';
person1.age = 30;

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'
};

const person3 = Object.assign({}, person1, person2);


To modify an object, you can access its properties using dot notation or bracket notation and
assign new values to them. You can also add or delete properties using the same syntax.
person1.age = 35;

person1['address'] = 'Los Angeles';

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
};

person.city = 'New York';


person['country'] = 'USA';

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();
}

doSomething(() => console.log('Task completed!'));


Return Statement
A function can return a value using the return keyword. If no value is returned, the function
returns undefined by default.
function sum(a, b) {
return a + b;
}

const result = sum(2, 3); // returns 5

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:

. : matches any single character except newline


* : matches zero or more occurrences of the preceding character or group
+ : matches one or more occurrences of the preceding character or group
? : makes the preceding character or group optional
[] : matches any character within the brackets
() : groups a set of characters together
For example, the regular expression pattern /[a-z]+\d?/ matches any sequence of one or more
lowercase letters followed optionally by a single digit.

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.

You might also like