Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

1

Web Programming Third Module Part-2


Advanced JavaScript

JavaScript Arrays
 JavaScript arrays are used to store multiple values in a single variable.
 Arrays can hold any data type, including numbers, strings, and objects.
 Arrays are indexed starting from 0, and you can access any element in the array using its
index.
 Here's an example of a JavaScript array:

var fruits = ['apple', 'banana', 'orange'];

 This array contains three elements: 'apple', 'banana', and 'orange'.


 You can access any element in the array using its index. For example, to access the first
element ('apple'), you would use the following code:

var firstFruit = fruits[0];

 This would set the variable `firstFruit` to 'apple'.


 You can also change the value of an element in the array by assigning a new value to its index.
 For example, to change the second element ('banana') to 'grape', you would use the following
code:

fruits[1] = 'grape';

 This would change the array to ['apple', 'grape', 'orange'].


 Example:
<!DOCTYPE html>
<html>
<body>

Web Programming_3rd_Module_Part2_SRT
2

<h1>JavaScript Arrays</h1>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.write(cars);
</script>
</body>
</html>

Objects
 In JavaScript, an object is a collection of properties that describe a thing.
 An object can contain properties that are either primitive values, other objects, or functions.
 Here's an example of a simple object:

var person = {
name: 'John',
age: 30,
city: 'New York'
};

 This object has three properties: `name`, `age`, and `city`.


 You can access any property in the object using dot notation or bracket notation.
 For example, to access the `name` property, you would use the following code:

var personName = person.name;

 This would set the variable `personName` to 'John'.


 You can also change the value of a property in the object by assigning a new value to its
key.
 For example, to change the `age` property to 31, you would use the following code:

person.age = 31;

Web Programming_3rd_Module_Part2_SRT
3

 This would change the object to `{ name: 'John', age: 31, city: 'New York' }`.
 You can also add new properties to an object by assigning a value to a new key.
 For example, to add a `country` property with the value 'USA', you would use the
following code:

person.country = 'USA';

 This would change the object to{name: 'John', age: 31, city: 'New York', country: 'USA'
}.
 Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<script>
var person = {
name: "John",
age: 30,
city: "New York"
};

document.write(person.name);
</script>

</body>
</html>

Numbers
 In JavaScript, numbers are a primitive data type that represent numeric values.

Web Programming_3rd_Module_Part2_SRT
4

 JavaScript numbers can be integers or floating-point numbers.


 Here's an example of a JavaScript number:

var myNumber = 42;

 This sets the variable `myNumber` to the integer value 42.


 You can perform mathematical operations on JavaScript numbers using arithmetic
operators like `+`, `-`, `*`, and `/`.
 For example, to add two numbers together, you would use the `+` operator:

var sum = 5 + 7;
 This sets the variable `sum` to the value 12.
 You can also use the `++` and `--` operators to increment and decrement a number by one,
respectively.
 JavaScript numbers also have special values like `NaN` (Not a Number) and `Infinity`.
 `NaN` is returned when a mathematical operation is undefined, such as dividing zero by
zero.
 `Infinity` is returned when a number exceeds the upper limit of the floating-point number
system.

 Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<script>
var x = 3.14;

Web Programming_3rd_Module_Part2_SRT
5

var y = 3;
document.write("The sum is "+(x+y));
</script>

</body>
</html>

Boolean
 In JavaScript, a boolean is a primitive data type that can have one of two values: `true` or
`false`.
 Here's an example of a JavaScript boolean:
var isRaining = true;
 This sets the variable `isRaining` to the value `true`.
 You can use boolean values in conditional statements like `if` statements and loops to
control the flow of your code.
 For example, you might use an `if` statement to check if it's raining before going outside:

if (isRaining) {
alert ('Bring an umbrella!');
} else {
alert ('No need for an umbrella.');
}

 This code would output an alert of 'Bring an umbrella!' if `isRaining` is `true`, and 'No
need for an umbrella.' if `isRaining` is `false`.
 You can also use boolean operators like `&&` (and), `||` (or), and `!` (not) to combine and
manipulate boolean values.

 Example:
<!DOCTYPE html>

Web Programming_3rd_Module_Part2_SRT
6

<html>
<body>

<h1>JavaScript Booleans</h1>

<script>
document.write( Boolean(10 > 9));
</script>

</body>
</html>

Strings
 In JavaScript, a string is a primitive data type that represents a sequence of characters.
 Here's an example of a JavaScript string:

var myString = 'Hello, world!';

 This sets the variable `myString` to the string value 'Hello, world!'.
 You can perform operations on JavaScript strings using string methods like `slice`,
`toUpperCase`, and `toLowerCase`.
 For example, you might use the `slice` method to extract a substring from a string:

var greeting = 'Hello, world!';


var name = greeting.slice(7);

 This sets the variable `name` to the string value 'world!'. You can also concatenate strings
together using the `+` operator:

var firstName = 'John';

Web Programming_3rd_Module_Part2_SRT
7

var lastName = 'Doe';


var fullName = firstName + ' ' + lastName;

 This sets the variable `fullName` to the string value 'John Doe'.
 Example:
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<script>
var text = "John Doe";
document.write(text);
</script>

</body>
</html>

Date
 In JavaScript, the `Date` object is used to work with dates and times.
 You can use the `Date` object to create a new date object with a specific date and time, or
to get the current date and time.
 Here's an example of creating a new date object with a specific date and time:

var myDate = new Date('2023-07-01T06:12:00');

 This sets the variable `myDate` to a `Date` object representing July 1st, 2023 at 6:12 AM.
 You can also use various methods of the `Date` object to get specific parts of the date and
time, such as the year, month, day, hour, minute, and second:

Web Programming_3rd_Module_Part2_SRT
8

var year = myDate.getFullYear(); // 2023


var month = myDate.getMonth(); // 6 (July is the 7th month, but months are zero-
indexed)
var day = myDate.getDate(); // 1
var hour = myDate.getHours(); // 6
var minute = myDate.getMinutes(); // 12
var second = myDate.getSeconds(); // 0
 You can also perform arithmetic operations on `Date` objects using the `set` methods to
add or subtract time intervals.
 Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Dates</h2>

<script>
var d = new Date();
document.write(d);
</script>

</body></html>

Event handling
 In JavaScript, event handling refers to the ability to respond to user actions, such as mouse
clicks or keyboard presses, by executing code in response to those actions.
 You can use event listeners to attach event handlers to HTML elements.
 Here's an example of attaching an event listener to a button element:

var myButton = document.getElementById('myButton');


myButton.addEventListener('click', function() {

Web Programming_3rd_Module_Part2_SRT
9

// code to execute when the button is clicked


});
 This attaches an event listener to the button element with the ID `myButton`.
 The second argument to `addEventListener` is a function that will be executed when the
button is clicked.
 You can also use event handlers to respond to events that are not user-initiated, such as the
`load` event that fires when a web page finishes loading:

window.addEventListener('load', function() {
// code to execute when the page finishes loading
});
 This attaches an event listener to the `window` object that will be executed when the `load`
event fires.
 In addition to the `click` and `load` events, there are many other events that you can handle
in JavaScript, such as `keydown`, `mousemove`, and `scroll`.
 You can find a full list of events in the JavaScript documentation.
 Here's a simple example of event handling in JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
</head>
<body>
<button id="myButton">Click me!</button>
<script>
var myButton =
document.getElementById('myButton');
myButton.addEventListener('click', function() {
alert('Button clicked!');
});

Web Programming_3rd_Module_Part2_SRT
10

</script>
</body>
</html>

 This code defines a button element with the ID `myButton`, and attaches an event listener
to it using the `addEventListener` method.
 The event listener is a function that displays an alert box when the button is clicked.
 When you open this HTML file in a web browser and click the button, you should see an
alert box that says "Button clicked!".

Javascript DOM
 The Document Object Model (DOM) is a programming interface for web documents.
 It represents the page so that programs can change the document structure, style, and content.

 When a web page is loaded, the browser creates a Document Object Model of the page, which
is an object-oriented representation of an HTML document that can be modified with a
scripting language such as JavaScript.
 With JavaScript and the DOM, you can:
- Access all elements on a web page as objects
- Change all HTML elements and attributes
- Add new HTML elements and attributes
- Remove existing HTML elements and attributes
- React to all existing HTML events in the page
- Create new HTML events in the page
 Here's an example of using JavaScript to change the text content of an HTML element:

<!DOCTYPE html>

<html>

Web Programming_3rd_Module_Part2_SRT
11

<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="myHeading">Hello, world!</h1>
<script>
var myHeading = document.getElementById('myHeading');
myHeading.textContent = 'Hello, DOM!';
</script>
</body>
</html>
 This code defines an HTML heading element with the ID `myHeading`, and uses the
`getElementById` method to get a reference to it in JavaScript.
 The `textContent` property is then used to change the text content of the heading to "Hello,
DOM!".
 When you open this HTML file in a web browser, you should see the text "Hello, DOM!"
displayed in the heading instead of "Hello, world!"
 [Refer DOM in 2nd Module].

Javascript RegEx
 A regular expression (regex or regexp for short) is a pattern that describes a set of strings.
 Regular expressions are used in many programming languages, including JavaScript, to
search for and manipulate text.
 In JavaScript, regular expressions are represented by the `RegExp` object. You can create a
regular expression in two ways:
1. Using a regular expression literal, which consists of a pattern enclosed between slashes:
var pattern = /hello/;
2. Using the `RegExp` constructor, which takes a pattern string as its argument:
var pattern = new RegExp('hello');

Web Programming_3rd_Module_Part2_SRT
12

 Once you have a regular expression, you can use it to search for matches in a string using
the `test` or `exec` methods:
var pattern = /hello/;
var text = 'hello, world!';
alert(pattern.test(text)); // output is true.
alert(pattern.exec(text)); //output is hello

 In this example, the regular expression `/hello/` is used to search for the string "hello" in
the text "hello, world!".
 The `test` method returns `true` because the pattern is found in the text.

 The `exec` method returns an array containing information about the first match, including
the matched text, its index in the input string, and the input string itself.

 Regular expressions can be very powerful, allowing you to search for complex patterns of
text and perform advanced search-and-replace operations.

 However, they can also be difficult to read and write, so it's important to use them
judiciously and with care.
 Here's a simple example of a regular expression in JavaScript:
var pattern = /hello/;
var text = 'hello, world!';
if (pattern.test(text)) {
alert('Found a match!');
}
 In this example, we create a regular expression `/hello/` and a string `text` that contains
the word "hello".
 We then use the `test` method of the regular expression object to check whether the pattern
occurs in the text. If it does, alert occurs.

Web Programming_3rd_Module_Part2_SRT
13

Javascript Validation
 JavaScript validation is the process of checking whether user input is valid and meets
certain criteria before it is submitted to a server or processed further.
 Validation is important to ensure that the data being submitted is accurate, complete, and
secure.
 JavaScript provides several ways to perform validation, including:

1. Client-side validation: This is validation that is performed in the user's web browser,
before the data is submitted to the server.
Client-side validation can provide immediate feedback to the user, and can help prevent
unnecessary server requests and page reloads.
Some common client-side validation techniques include using regular expressions to
check the format of input fields (e.g. email addresses, phone numbers), checking that
required fields are filled in, and checking that numeric fields contain valid numbers.

2. Server-side validation: This is validation that is performed on the server, after the data
has been submitted.
Server-side validation is important to ensure that the data is valid and secure, even if
client-side validation has been bypassed or disabled.
Server-side validation can check for things like SQL injection attacks, cross-site scripting
(XSS) attacks, and other security vulnerabilities.

3. Third-party validation libraries: There are many third-party JavaScript libraries


available that can help with validation, such as jQuery Validation, Validator.js etc.
These libraries can provide additional validation features and can save time and effort by
providing pre-built validation rules and error messages.

 In general, validation is an important part of building secure and reliable web applications,
and should be implemented carefully and thoughtfully.

 Here's a simple example of client-side validation in JavaScript:

Web Programming_3rd_Module_Part2_SRT
14

<html>
<head><title>Client-side Validation</title></head>
<body>
<form onsubmit="return validateForm()" action=”next.html”>
<label>Enter Name</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>

<script>
function validateForm()
{
var name = document.getElementById("name").value;
if (name == "" )
{
alert("Please fill the name field.");
return false;
}
return true;
}
</script>
</body>
</html>

Output

Web Programming_3rd_Module_Part2_SRT
15

 In this example, we have a simple HTML form one input field: a name field.
 We've also added an `onsubmit` attribute to the form that calls a JavaScript function
`validateForm()` when the form is submitted.
 In the `validateForm()` function, we get the value of the name field using
`document.getElementById()`.
 If the field is empty, we display an error message using `alert()` and return `false` to prevent
the form from being submitted.
 If the name field is filled, we return `true` to allow the form to be submitted.

Javascript Math
 The JavaScript Math object allows you to perform mathematical tasks on numbers.
 The syntax for any Math property is : Math.property.
 Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.PI</h2>
<script>
document.write(Math.PI);
</script>
</body>
</html>
 Some math properties are the following:
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E

Web Programming_3rd_Module_Part2_SRT

You might also like