Web Framework 1 PDF
Web Framework 1 PDF
What is framework?
2.1 Introduction
2.2 What is Node JS and its advantages
2.3 Traditional Web Server Model
2.4 Node JS Process model
2.5 Installation of Node JS
2.6 Node JS event loop
3 Node JS Modules
3.1 Functions
3.2 Buffer
3.3 Module and Module Types
3.4 Core Module, Local Module
3.5 Directories as module
3.5 Module.exports
4 Node Package Manager
4.1 What is NPM?
4.2 Installing package locally
4.3 Adding dependencies in package.json
4.4 Installing packages globally
4.5 Updating packages
4.6 Managing Dependencies
5 Web Server
5.1 Creating Web Server
5.2 Handling HTTP requests
5.3 Sending Requests
5.4 HTTP Streaming
6. File System
6.1 FS Model
6.2 Files and Directories
6.6 Streams
6.4 Reading and Writing Files
6.5 Reading and Writing Directories
6.6 Other File Operations
7 Events
7.1 Asynchronous JS
7.2 Asynchronous control flow with
callbacks
7.3 Promises
7.4 EventEmitter Class
7.5 ASync/Await
7.6 Returning Event Emitter
7.7 Inheriting Events
8. Working with Databases
Data types
Primitive Composite
Data Types Data Types
Number Arrays
String Objects
Boolean(True,False)
Primitive Data Types
While naming your variables in JavaScript, keep the following rules in mind:
You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For
example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
JavaScript variable names are case-sensitive. For
example, Name and name are two different variables.
JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following
table. They cannot be used as JavaScript variables, functions, methods,
loop labels, or any object names.
abstract else instanceof switch
boolean enum int synchronized
Oprands Operator
➢ The list of operators is given below:
•Arithmetic Operators
•Relational Operators
•Bitwise Operators
•Logical Operators
•Assignment Operators
•String Operators
JavaScript Arithmetic Operators
JavaScript Arithmetic operators are used to perform arithmetic operations
like addition, subtraction, multiplication, etc.
All the arithmetic operators have been listed in the below table.
<html>
<body>
<script type = "text/javascript">
<!-- var a = 33; var b = 10; 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);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
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> Set the variables to different values and then
try... </body>
</html>
JavaScript Relational Operators
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true Set the variables
to different values and different
operators and then try...
JavaScript Bitwise Operators
The logical gate's functions are used as logical operators in JavaScript. These
operators are also used in Flow control.
JavaScript Assignment Operators
These are the operators used while assigning the values to the variables.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Flow Control statements in java
While writing a program, there may be a situation when you need to adopt
one out of a given set of paths.
In such cases, you need to use conditional statements that allow your
program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform
different actions based on different conditions.
If-else conditional statement
Syntax-
if (expression)
{
//Statement(s) to be executed if expression is true
} else
{ //Statement(s) to be executed if expression is false
}
Example
<html>
<body>
<script type = "text/javascript">
<!-- var age = 15; if( age > 18 )
{ document.write("<b>Qualifies for driving</b>");
}
else
{ document.write("<b>Does not qualify for driving</b>"); } //-->
</script> <p>Set the variable to different value and then
try...</p>
</body>
</html>
if...else if... statement
<html>
<body>
<script type = "text/javascript">
<!-- var book = "maths"; if( book == "history" )
{ document.write("<b>History Book</b>"); }
else if( book == "maths" )
{ document.write("<b>Maths Book</b>"); }
else if( book == "economics" )
{ document.write("<b>Economics Book</b>"); }
else { document.write("<b>Unknown Book</b>"); } //-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output:
Maths Book Set the variable to
different value and then try...
JavaScript Switch
default: //default code to be executed //if none of the above case executed }
switch statement contains a literal value as expression. So, the case that
matches a literal value will be executed
The value of the expression is compared with the values of each case.If there
is a match, the associated block of code is executed.If there is no match, the
default code block is executed.
This expression may be string or number
The break statements indicate the end of a particular case. If they were
omitted, the interpreter would continue executing each statement in each of
the following cases.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Loops in JavaScript
➢ There are times when we would want to perform a certain operation a
certain number of times, like if we have a list of employees with their
salaries and we have to calculate their income tax. Now the formula
for getting the income tax is the same for all employees, so we can
have a loop and execute the code statements with different inputs.
➢ Similarly, for a use case like printing the mathematical table of a
number like 2, we can simply have a loop in place to keep on
multiplying the .
➢ The loop statements are executed until the condition becomes false.
When the condition becomes false, the execution of loop stops.
In JavaScript, there are various types of loops.
•for loop
•for-in loop
•for-of loop
•while loop
•do-while loop
For loop
➢ If you want to execute statements for a specific number of times then you can use the
JavaScript for loop, which lets you iterate the statements for a fixed number of times.
➢ Syntax
for(initialization; condition; iteration)
{
// statements
}
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
For-in loop
➢ If you want to loop through the properties of a JavaScript Object then you can use the
JavaScript for…in loop.
➢ The for/in loop automatically iterates over the fields of an object and the loop stops when all the
fields are iterated
➢ Syntax
for(key in object)
{
// code statements
}
➢ When the loop will run, every time the key will get the value of the key using which we can
access the value against it in the object.
➢ In JavaScript, objects are in format {"key1":"value1","key2":"value2", ...} for which the for/in
loop can be used to iterate over all the fields of JavaScript object.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For/In Loop</h2>
<p>The for/in statement loops through the properties of an object.</p>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person)
{
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Output
The for/in statement loops through the properties of an object.
John Doe 25
For-of loop
The JavaScript for/of loop lets you loop through the values of an iterable
object like an array, strings and more.
Syntax
for(variable of iterable)
{
//code here
}
Example
<!DOCTYPE html>
<html>
<body>
<script>
var cars = ['BMW', 'Volvo', 'Mini'];
var x;
for (x of cars) {
document.write(x + "<br >");
}
</script>
</body>
Output:
The for/of statement loops through the
values of an iterable object.
BMW
Volvo
Mini
While loop
The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known.
Syntax
while (condition)
{
code to be executed
}
Example of while loop
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
do-while
➢ Just like the while loop, the do...while loop lets you iterate the code block as
long as the specified condition is true.
➢ In the do-while loop, the condition is checked after executing the loop. So,
even if the condition is true or false, the code block will be executed for at
least one time.
➢ Syntax
do {
// code block to be executed
}
while (condition);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Do/While Loop</h2>
<p id="demo"></p>
<script>
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
Function
The code inside the function will execute when "something" invokes (calls)
the function:
1. When an event occurs (when a user clicks a button)
2. When it is invoked (called) from JavaScript code
3. Automatically (self invoked)
Function Return
➢ When JavaScript reaches a return statement, the function will stop executing.
➢ If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
➢ Functions often compute a return value.
➢ The return value is "returned" back to the "caller":
➢ functions can be parameterized and non-parameterized
➢ A function that does not take any parameters/inputs is known as non-
parametrized function.
➢ A function that takes parameters/inputs which must be defined within
parenthesis is known as a parameterized function.
➢ When we call a function, we can provide custom values for these
parameters which are then used in function defintion.
➢ Use return statement.
➢ we can categorize functions into two category:
Function
function_name(parameter-1, parameter-
2,...parameter-n)
{
// function body
}
After creating a function, we can call it anywhere in our script. The syntax for
calling a function is given below:
➢ Functions that are provided by JavaScript itself as part of the scripting language, are known
as built-in functions.
➢ JavaScript provides a rich set of the library that has a lot of built-in functions.
➢ Some examples of the built-in functions are : alert(), prompt(), parseInt(), eval() etc.
We can also create function with default parameters
For example-
function printValue(a=1, b)
{
Document.write("a = " + a + " and b = " + b);
}
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.
When an alert box pops up, the user will have to click "OK" to proceed.
<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes - 2
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
JavaScript Popup Boxes - 3
Prompt Box
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK“, the box returns the input value. If the user clicks "Cancel“,
the box returns null.
Prompt Box Example
<script>
x=prompt (“Adınızı Yazınız”, “ ”)
document.write(“Merhaba <br>”,+x)
</script>
Events
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & onkeydown & onkeyup When the user press and then release the key
Keyup
Form Event
change onchange When the user modifies or changes the value of a form element
Window/Document events
load onload When the browser finishes the loading of the page
unload onunlo When the visitor leaves the current webpage, the browser unloads it
ad
resize onresiz When the visitor resizes the window of the browser
e
Example of click event
<html>
<body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("This is javascript program");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
Output:
Example of MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("Mouseover event");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Output:
Example of Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
Output:
Example of keydown event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Output:
Example of loadEvent()
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
Output:
Regular Expression
➢ A regular expression is a sequence of characters that forms a search
pattern.
➢ The search pattern can be used for text search and text replace
operations.
➢ A regular expression can be a single character, or a more complicated
pattern.
➢ Regular expressions can be used to perform all types of text search
and text replace operations.
Regular expressions are frequently used to test whether or not a string
entered in an HTML form has a certain format.
For example, you want to test if a user entered a string that contains 3
consecutive digits.
\d\d\d
JavaScript provides regular expression capabilities through instances of the built-in
RegExp object.
Syntax
Modifier Description
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word
like this: \bWORD, or at the end of a
word like this: WORD\b
\uxxxx Find the Unicode character specified by
the hexadecimal number xxxx
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more
occurrences of n
n? Matches any string that contains zero or one
occurrences of n
➢ The test() method is a RegExp expression method.
➢ It searches a string for a pattern, and returns true or false, depending on the result.
➢ The following example searches a string for the character "e":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search for an "e" in the next paragraph:</p>
<p id="p01">The best things in life are free!</p>
<p id="demo"></p>
<script>
text = document.getElementById("p01").innerHTML;
document.getElementById("demo").innerHTML = /e/.test(text);
</script>
</body>
</html>
Array and Objects in JavaScript
Example-
<html>
<body> Output:
<script>
var emp=["Sonoo","Vimal","Ratan"]; Sonoo
for (i=0;i<emp.length;i++){ Vimal
document.write(emp[i] + "<br/>"); Ratan
}
</script>
</body>
</html>
JavaScript Array directly (new keyword)
➢ Syntax
➢ new keyword is used to create instance of array.
<html>
<body>
<script> Output:
Arun
var i; Varun
var emp = new Array(); John
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] +
"<br>");
}
</script>
JavaScript array constructor (new keyword)
you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly
Example
Output:
<html>
<body> Jai
<script> Vijay
var emp=new Array("Jai","Vijay","Smith"); Smith
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Types of array
Array
Associative
Index array
array
Index Array:
➢ This type of array indexed numerically
➢ By default index of first element is 0.
➢ All are above examples of indexed array
Array Properties
Properties Description
Method Description
concat() Merge two or more arrays, and
returns a new array.
copyWithin() Copies part of an array to another
location in the same array and
returns it.
<html>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and get a list of car models</p>
<button onclick="arrayToString()">Try it</button>
<p id="text"></p>
</body>
Javascript funcion
function arrayToString()
{ var cars = ["Audi", "Mazda", "BMW", "Toyota"];
document.getElementById("text").innerHTML = cars.toString();
// output: Audi, Mazda, BMW, Toyota
}
Join method
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the join method works</p>
<button onclick="carsArrayJoin()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsArrayJoin() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
document.getElementById("text").innerHTML = cars.join(" - ");
}
Output:
Pop()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the pop method works</p>
<button onclick="carsPop()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsPop() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.pop();
document.getElementById("text").innerHTML = cars.toString();
}
Output:
Push()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the push method works</p>
<button onclick="carsPush()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsPush() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.push("new");
document.getElementById("text").innerHTML = cars.toString();
}
Output:
Shift()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button to remove the first element of the array</p>
<button onclick="carsShift()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsShift() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.shift();
document.getElementById("text").innerHTML = cars.toString();
}
Output:
:
Unshift()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the unshift method works</p>
<button onclick="carsUnshift()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsUnshift() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.unshift("new");
document.getElementById("text").innerHTML = cars.toString();
}
Output:
Splice()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the splice method works</p>
<button onclick="spliceArray()">Try it</button>
<p id="text"></p>
</body>
</html>
JavaScript function
function spliceArray() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.splice(2, 0, "new", "newer");
document.getElementById("text").innerHTML = cars.toString();
}
Output:
Sort()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button to output sorted array</p>
<button onclick="sort()">Try it</button>
<p id="text"></p>
</body>
</html>
JavaScript function()
function sort() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.sort();
document.getElementById("text").innerHTML = cars.toString();
}
Output:
Reversearray()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button to output sorted and reversed array</p>
<button onclick="reverseArray()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function reverseArray() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.sort();
cars.reverse();
document.getElementById("text").innerHTML =
cars.toString();
}
Output:
Concat()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>See how you can add two arrays</p>
<button onclick="concatArrays()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function concatArrays() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
var people = ["Joe", "Leona"];
var joined = cars.concat(people);
document.getElementById("text").innerHTML = joined.toString();
}
Output:
Slice()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click and look how the slice method works</p>
<button onclick="sliceArrays()">Try it</button>
<p id="text"></p>
</body>
</html>
JavaScript function
function sliceArrays() {
var cars = ["Audi", "Mazda", "BMW", "Toyota", "Suzuki"];
var myCars = cars.slice(1, 3);
document.getElementById("text").innerHTML =
myCars.toString();
}
Output:
Associative Array
Example:
JavaScript provides support for working with dates and time through the Date
object.
Date object allows you to get and set the year, month, day, hour, minute,
second and millisecond fields.
Date object can be created as :
var today = new Date( );
Methods of Date
Date() Returns current date and time.
➢ Example
Properties Description
length It returns the length of the string.
prototype It allows you to add properties and
methods to an object.
constructor It returns the reference to the
String function that created the
object.
String Methods
Methods Description
charAt() It returns the character at the
specified index.
charCodeAt() It returns the ASCII code of the
character at the specified position.
concat() It combines the text of two strings
and returns a new string.
Methods Description
indexOf() It returns the index within the calling String
object.
match() It is used to match a regular expression
against a string.
replace() It is used to replace the matched substring
with a new substring.
search() It executes the search for a match between a
regular expression.
slice() It extracts a session of a string and returns a
new string.
split() It splits a string object into an array of strings
by separating the string into the substrings.
toLowerCase() It returns the calling string value converted
lower case.
toUpperCase() Returns the calling string value converted to
uppercase.
Example of String object
<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>
Output:
Boolean object in JavaScript
In the HTML DOM, the Element object represents an HTML element, like P,
DIV, A, TABLE, or any other HTML element.
Properties
property Description
Id Sets or return id of element
Value Return value of element
innerHtml Sets or return content of element
Length Return no of entries in element array
tagName Return tagname of element as string
in uppercase
Examples
Example 1
Example 2:
<html>
<head>
<script type=“text/javascript”>
Function wel()
{
Var cname=document.getElementById(‘cname’);
Var bt=document.getElementById(‘btxt’);
HTML
Bt.innerHtml=cname.value;
}
</script>
</head>
<body>
<p>Welcome to<b id=“btxt’>City</b></p>
City Name<input type=:text” id=“cname”><br>
<input type=“button” onclick=“wel()” value=“Enter”>
</body>
</html>
Anchor Object
Property Description
href Sets or return value of href attribute
of link
name Sets or return value of name
attribute of link
Form Object
Form object represents form which is used to collect user input through
elements like text fields, check box and radio button, select option, text
area, submit buttons and etc.. and pass this data from and to server.
Form object properties
Property Description
Action It sets and returns the value of the
action attribute in a form.
enctype It sets and returns the value of the
enctype attribute in a form.
Length It returns the number of elements in a
form.
Method It sets and returns the value of the
method attribute in a form that is GET
or POST.
Methods
Method Description
reset() It resets a form.
submit() It submits a form.
Hidden Object
Property Description
Name It sets and returns the value of the
name attribute of the hidden input
field.
Type It returns type of hidden input
element of form
Password Object
Password object represents a single-line password field in an HTML form.
The content of a password field will be masked – appears as spots or asterisks
in the browser using password object
Syntax: <input type= “password”>
Property Description
defaultValue It sets or returns the default value of
a password field.
maxLength It sets or returns the maximum
number of characters allowed in a
password filed.
Name It sets or returns the value of the
name attribute of a password field.
readOnly It sets or returns whether a password
fields is read only or not.
Size It sets or returns the width of a
password field.
Value It sets or returns the value of the
attribute of the password field.
Methods
Method Description
Select() It selects the content of a password
field.
Checkbox Object
Check box object represents a checkbox in an HTML form.
It allows the user to select one or more options from the available choices.
Syntax:
<input type= “checkbox”>
Properties Description
Name It sets or returns the name of the
checkbox.
Type It returns the value “check”.
Value It sets or returns the value of the
attribute of a checkbox.
checked It sets or returns the checked state of
a checkbox.
defaultChecked It returns the default value of the
checked attribute.
Checkbox Object Methods
Method Description
click() It sets the checked property.
Select Object
<select> … </select>
Collection Description
options It returns a collection of all the
options in a dropdown list.
Select Object Properties
Property Description
Length It returns the number of options in a
dropdown list.
selectedIndex It sets or returns the index of the
selected option in a dropdown list.
Type It returns a type of form element.
name It returns the name of the selection
list.
Methods
Method Description
add() It adds an option to a dropdown list.
remove() It removes an option from a dropdown
list.
Option Object
Option object represents an HTML <option> element.
It is used to add items to a select element.
Syntax
Methods Description
blur() It removes the focus from
the option.
focus() It gives the focus to the
option.
Example
<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
</head> Output:
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option> Your favourite fruit is
<option mango
value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select"
onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>
Radio Object
Radio object represents a radio button in an HTML form.
Syntax: <input type= “radio”>
Property Description
Checked It sets or returns the checked state of
a radio button.
defaultChecked Returns the default value of the
checked attribute.
Name It sets or returns the value of the
name attribute of a radio button.
Type It returns the type of element which is
radio button.
Value It sets or returns the value of the
radio button.
Radio Object Methods
Method Description
blur() It takes the focus away from the radio
button.
click() It acts as if the user clicked the button.
focus() It gives the focus to the radio button.
Text Object
➢ Text object represents a single-line text input field in an HTML form.
➢ Text Object Properties
Property Description
Value It sets or returns the value of the text
field.
defaultValue It sets or returns the default value of a
text field.
Name It sets or returns the value of the name
attribute of a text field.
maxLength It sets or returns the maximum number of
characters allowed in a text field.
Function doThing(other)
{
let x=7;
other();
}
function hello()
{
document.write(“hello”);
}
doThing(hello);
In –buit callback function
setTimeout()
➢ The setTimeout() method calls a function or evaluates an expression after a
specified number of milliseconds.
➢ Syntax
setTimeout(function, milliseconds, param1, param2, ...)
Parameter Description
function Required. The function that will be
executed
milliseconds Optional. The number of milliseconds
to wait before executing the code. If
omitted, the value 0 is used
param1, param2, ... Optional. Additional parameters to
Example
setTimeout(hello,2000,’Ranjit’);
Function doThing(other)
{
Let x=7;
Let name=‘steve’;
Other(name);
}
Function hello(nm,index,arr)
{
Document.write(“hello”,nm);
}
doThing(hello);
}
Foreach loop
➢ The forEach() method calls a function once for each element in an array, in order.
➢ Syntax
Parameter Description
function(currentValue, index, arr) Required. A function to be run for
each element in the array.
Function arguments:
Argument Description
currentValue Required. The
value of the
current element
index Optional. The
array index of the
current element
thisValue Optional. A value to be passed to the
function to be used as its "this" value.
If this parameter is empty, the value
"undefined" will be passed as its "this"
value
Example
Let names[‘Amir’,’Sarukh’,’Salman’,’Ajay’);
names.foreach(hello);
Function doThing()
{
Let x=7;
Let name=‘steve’;
Other(name);
}
Function hello(nm,idx,arr)
{
Document.write(“hello”,nm);
}
doThing(hello);
}
Promises
Promises are used to handle asynchronous operations in JavaScript.
They are easy to manage when dealing with multiple asynchronous
operations
Multiple callback functions would create callback hell that leads to
unmanageable code.Events were not good at handling asynchronous
operations
Promises are the ideal choice for handling asynchronous operations in
the simplest manner.
They can handle multiple asynchronous operations easily and provide
better error handling than callbacks and events.
Benefits of Promises
promise.
then(function () {
console.log('Success, You are a pass);
}).
catch(function () {
console.log('Some error has occured');
});
Promise ConsumersPromises can be consumed by registering functions
using .then and .catch methods.
1. then()
then() is invoked when a promise is either resolved or rejected.
Parameters:
then() method takes two functions as parameters.
I. First function is executed if promise is resolved and a result is received.
II. Second function is executed if promise is rejected and an error is received.
(It is optional and there is a better way to hanlde error using .catch() method
Syntax
)
.then(function(result){ //handle success },
function(error){ //handle error }
Example:promise resolved
promise
.then(function(successMessage)
{
//success handler function is invoked
console.log(successMessage);
}, function(errorMessage) {
console.log(errorMessage);
})
2. catch()
.catch(function(error){ //handle
error })
Example
promise
.then(function(successMessage) {
console.log(successMessage);
})
.catch(function(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});