You are on page 1of 19

Web Technology

Unit-4 - Java Script


Introduction:
JavaScript is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages. It is an interpreted, full-fledged programming language
that enables dynamic interactivity on websites when applied to an HTML document.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending
on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

History
JavaScript language comes from the times when early web browsers were being
developed. Netscape Communications company in 1994 created Netscape Navigator that
became the most popular web browser in the 90s.
Company’s board quickly realized that browsers should allow create more dynamic websites
and do some activities that do server-side languages, like input validation. First Netscape
Communications cooperate with Sun Microsystems to use in Netscape Navigator Sun’s
programming language Java. Then they wanted adopting and embedding a existing
programming language like Scheme, Perl or Python. Eventually they decided to create scripting
language that would complement Java and has a similar syntax.
In 1995 Netscape Communications employed Brendan Eich to develop scripting language for
web browser. Eich prepared it in a very short time. First version of new language had Mocha
name, whereas official version used in Netscape Navigator 2 beta version was called LiveScript.
JavaScript was invented by Brendan Eich in 1995.
It was developed for Netscape 2, and became the ECMA-262 standard in 1997.
After Netscape handed JavaScript over to ECMA, the Mozilla foundation continued to develop
JavaScript for the Firefox browser. Mozilla's latest version was 1.8.5. (Identical to ES5).

Year ECMA Browser

1995 JavaScript was invented by Brendan Eich

1996 Netscape 2 was released with JavaScript 1.0

1997 JavaScript became an ECMA standard (ECMA-262)

1997 ES1 ECMAScript 1 was released

1997 ES1 IE 4 was the first browser to support ES1

1998 ES2 ECMAScript 2 was released

1998 Netscape 42 was released with JavaScript 1.3

1999 ES2 IE 5 was the first browser to support ES2

1999 ES3 ECMAScript 3 was released

2000 ES3 IE 5.5 was the first browser to support ES3

2008 ES4 ECMAScript 4 was abandoned

2009 ES5 ECMAScript 5 was released

2011 ES5 IE 9 was the first browser to support ES5 *

2014 ES5 Full support for ES5 in all browsers

2015 ES6 ECMAScript 6 was released

2018 ES6 Full support for ES6 in all browsers **


Syntax:
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.

<html>
<body>
<script language = "javascript" type =
"text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

Variables In JavaScript:
A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.
1. A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only.
2. A JavaScript global variable is accessible from any function. A variable i.e. declared outside
the function or declared with window object is known as global variable.

In JavaScript, a variable can be declared using var, let, const keywords.

var let const

The scope of The scope of a let variable is block The scope of a const variable is
a var variable is scope. block scope.
functional scope.

It can be updated It can be updated but cannot be re- It cannot be updated or re-declared
and re-declared declared into the scope. into the scope.
into the scope.

It can be declared It can be declared without It cannot be declared without


without initialization. initialization.
initialization.
It can be accessed It cannot be accessed without It cannot be accessed without
without initialization otherwise it will give initialization, as it cannot be
initialization as its ‘referenceError’. declared without initialization.
default value is
“undefined”.

hoisting done, with Hoisting is done, but not initialized Hoisting is done, but not initialized
initializing as (this is the reason for the error (this is the reason for the error
‘default’ value when we access the let variable when we access the const variable
before declaration/initialization before declaration/initialization

Data Types In Javacript:


JavaScript is a dynamically typed (also called loosely typed) scripting language. In JavaScript,
variables can receive different data types over time. Datatypes are basically types of data that
can be used and manipulated in a program. A variable in JavaScript can contain any data. This
means that a variable at one time can be a number and at another be a string.
Primitive Data Types
The predefined data types provided by JavaScript language are known as primitive data types.
Primitive data types are also known as in-built data types.
 Number: JavaScript numbers are always stored in double-precision 64-bit binary format
IEEE 754. Unlike other programming languages, you don’t need int, float, etc to declare
different numeric values.
 String: JavaScript Strings are similar to sentences. They are made up of a list of
characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks”
etc.
 Boolean: Represent a logical entity and can have two values: true or false.
 Null: This type has only one value that is null.
 Undefined: A variable that has not been assigned a value is undefined.
 Symbol: Symbols return unique identifiers that can be used to add unique property keys
to an object that won’t collide with keys of any other code that might add to the object.
 BigInt: BigInt is a built-in object in JavaScript that provides a way to represent whole
numbers larger than 253-1.
Non-Primitive Data Types -- The data types that are derived from primitive data types of the
JavaScript language are known as non-primitive data types. It is also known as derived data
types or reference data types.
 Object: It is the most important data type and forms the building blocks for modern
JavaScript.

Statements In JavaScript:
JavaScript statements are the commands to tell the browser to what action to perform.
Statements are separated by semicolon (;).
Following table shows the various JavaScript Statements −

Statement Description

The if statement is the fundamental control statement that allows JavaScript to make
If else
decisions and execute statements conditionally.

The purpose of a while loop is to execute a statement or code block repeatedly as long
While
as expression is true. Once expression becomes false, the loop will be exited.

Block of statements that are executed at least once and continues to be executed
do while
while condition is true.

Same as while but initialization, condition and increment/decrement is done in the


for
same line.

for in This loop is used to loop through an object's properties.

The continue statement tells the interpreter to immediately start the next iteration of
continue
the loop and skip remaining code block.

The break statement is used to exit a loop early, breaking out of the enclosing curly
break
braces.

return Return statement is used to return a value from a function.

var Used to declare a variable.


try A block of statements on which error handling is implemented.

catch A block of statements that are executed when an error occur.

throw Used to throw an error.

Operators:
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

+ (Addition)
1 Adds two operands
Ex: A + B will give 30

- (Subtraction)
2 Subtracts the second operand from the first
Ex: A - B will give -10

* (Multiplication)
3 Multiply both operands
Ex: A * B will give 200

/ (Division)
4 Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

++ (Increment)
6 Increases an integer value by one
Ex: A++ will give 11

-- (Decrement)
7 Decreases an integer value by one
Ex: A-- will give 9

Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
1
becomes true.
Ex: (A == B) is not true.

!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,
2
then the condition becomes true.
Ex: (A != B) is true.

> (Greater than)


Checks if the value of the left operand is greater than the value of the right
3
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than the value of the right operand,
4
if yes, then the condition becomes true.
Ex: (A < B) is true.

>= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the value of the
5
right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

<= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of the
6
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

&& (Logical AND)


1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
3
Logical NOT operator will make it false.
Ex: ! (A && B) is false.

Assignment Operators
JavaScript supports the following assignment operators −

Sr.No. Operator & Description

= (Simple Assignment )
1 Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

+= (Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left
2
operand.
Ex: C += A is equivalent to C = C + A

−= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the
3
left operand.
Ex: C -= A is equivalent to C = C - A

*= (Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the result to the
4
left operand.
Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
5
operand.
Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment)


6 It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be
of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.

Functions In JavaScript:
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of code
each time to perform a common task.
JavaScript Function Syntax
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}

JavaScript Functions can have 0 or more arguments.


Example:
Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

JavaScript Array:
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that we don't
have to provide value explicitly.
The example of creating object by array constructor is given below.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Output of the above example
Jai
Vijay
Smith
JavaScript Array Methods

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided
function conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index
of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index
of the last match.

map() It calls the specified function for every array element and returns the new
array

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and
initial) reduces the array to a single value.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

toString() It converts the elements of a specified array into string form, without
affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).

2) By creating instance of Object


The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
101 Ravi 50000

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
Output of the above example
103 Vimal Jaiswal 30000

JavaScript Object Methods

Methods Description

Object.assign() This method is used to copy enumerable and own


properties from a source object to a target object
Object.create() This method is used to create a new object with the
specified prototype object and properties.

Object.entries() This method returns an array with arrays of the key, value
pairs.

Object.freeze() This method prevents existing properties from being


removed.

Object.getPrototypeOf() This method returns the prototype of the specified object.

Object.is() This method determines whether two values are the same
value.

Object.isSealed() This method determines if an object is sealed.

Object.keys() This method returns an array of a given object's own


property names.

Object.values() This method returns an array of values.

JavaScript Dialogue Boxes


Dialogue boxes are a kind of popup notification, this kind of informative functionality is used to
show success, failure, or any particular/important notification to the user.
JavaScript uses 3 kinds of dialog boxes:
 Alert
 Prompt
 Confirm
These dialog boxes can be of very much help in making our website look more attractive.
Alert Box: An alert box is used on the website to show a warning message to the user that
they have entered the wrong value other than what is required to fill in that position.
Nonetheless, an alert box can still be used for friendlier messages. The alert box gives only one
button “OK” to select and proceed.
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 on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false and will show null.
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 the OK button, the window method
prompt() will return the entered value from the text box. If the user clicks the Cancel button,
the window method prompt() returns null.

JavaScript – DOM (Document Object Model)


The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page
The Document Object Model (DOM) is a programming interface for HTML(HyperText Markup
Language) and XML(Extensible markup language) documents. It defines the logical structure of
documents and the way a document is accessed and manipulated.
DOM is a way to represent the webpage in a structured hierarchical way so that it will become
easier for programmers and users to glide through the document. With DOM, we can easily
access and manipulate tags, IDs, classes, Attributes, or Elements of HTML using commands or
methods provided by the Document object. Basically Document Object Model is an API that
represents and interacts with HTML or XML documents.
Why DOM is required?
HTML is used to structure the web pages and Javascript is used to add behavior to our web
pages. When an HTML file is loaded into the browser, the javascript can not understand the
HTML document directly. So, a corresponding document is created(DOM). DOM is basically the
representation of the same HTML document but in a different format with the use of objects.
Javascript interprets DOM easily i.e javascript can not understand the tags(<h1>H</h1>) in
HTML document but can understand object h1 in DOM. Now, Javascript can access each of the
objects (h1, p, etc) by using different functions.
Structure of DOM: DOM can be thought of as a Tree or Forest(more than one tree). The
term structure model is sometimes used to describe the tree-like representation of a
document. Each branch of the tree ends in a node, and each node contains objects Event
listeners can be added to nodes and triggered on an occurrence of a given event.
Representation of the DOM
 Window Object: Window Object is object of the browser which is always at top of the
hierarchy. It is like an API that is used to set and access all the properties and methods
of the browser. It is automatically created by the browser.
 Document object: When an HTML document is loaded into a window, it becomes a
document object. The ‘document’ object has various properties that refer to other
objects which allow access to and modification of the content of the web page. If there
is a need to access any element in an HTML page, we always start with accessing the
‘document’ object. Document object is property of window object.
 Form Object: It is represented by form tags.
 Link Object: It is represented by link tags.
 Anchor Object: It is represented by a href tags.
 Form Control Elements:: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
Methods of Document Object:
 write(“string”): Writes the given string on the document.
 getElementById(): returns the element having the given id value.
 getElementsByName(): returns all the elements having the given name value.
 getElementsByTagName(): returns all the elements having the given tag name.
 getElementsByClassName(): returns all the elements having the given class name.

You might also like