Unit IV, Javascript Basics
Unit IV, Javascript Basics
Javascript Basics
Prepared by
Binayak Maharjan
Introduction to Scripting Language
Introduction to scripting language
● A scripting language is a programming language designed for integrating and
communicating with other programming languages.
● A scripting language is a programming language used to automate tasks, control
other software, or create dynamic content in applications or websites.
● Some of the most widely used scripting languages are JavaScript, VBScript, PHP,
Perl, Python, Ruby, ASP, and Tcl.
● Uses:
○ Web Development: JavaScript for client-side interactivity, PHP for
server-side processing.
○ Task Automation: Python or Bash for system tasks.
○ Game Development: Lua in gaming engines.
Client side vs server side scripting language
Introduction to javascript
● Javascript is a dynamic computer programming language.
● It is lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and make
dynamic pages.
● It is an interpreted programming language with object-oriented capabilities.
● JavaScript is very easy to implement because it is integrated with HTML.
● It is open and cross platform.
● JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript.
Features of javascript
● Lightweight and Interpreted: JavaScript is executed directly in the browser
without the need for compilation.
● Client-Side Scripting: Runs in the user’s browser to create interactive and
dynamic web pages.
● Event-Driven Programming: Handles events like clicks, hovers, and form
submissions efficiently.
● Dynamic Typing: Variables can hold different data types, and types are
determined at runtime.
● Object-Oriented: Supports objects, prototypes, and inheritance for building
reusable code.
Features of javascript
● DOM Manipulation: Allows direct interaction with HTML and CSS to update
web content dynamically.
● Extensive Libraries and Frameworks :Includes powerful frameworks like
React, Angular, and [Link] for web development.
● Integration with Other Technologies: Works seamlessly with HTML, CSS, and
server-side languages like PHP or [Link].
● Platform Independence: Runs on any browser or environment with a
JavaScript engine (e.g., [Link]).
Advantages of javascript
● Executes on the client-side, reducing server load.
● Easy to learn with simple syntax.
● Runs quickly as it's interpreted directly in the browser.
● Enables dynamic and interactive web content.
● Compatible with all major browsers and platforms.
● Offers a rich ecosystem of libraries and frameworks.
● Versatile for both client-side and server-side programming.
● Allows real-time DOM manipulation for dynamic pages.
● Efficiently handles events like clicks and inputs.
Limitations of javascript
● Behavior can vary across browsers, requiring compatibility checks.
● Vulnerable to security issues like XSS if not managed well.
● Cannot directly access the local file system for security reasons.
● Limited to single-threaded execution, affecting heavy computations.
● Debugging errors in large-scale projects can be challenging.
● Relies on browser settings, which may disable JavaScript.
● Loose typing can lead to unexpected behavior.
● Performance may degrade with poorly optimized scripts.
What javascript can do and cannot?
What javascript can do?
● Create Dynamic Web Pages: Modify HTML and CSS in real-time using the DOM.
● Event Handling: Respond to user actions like clicks, keypresses, and mouse
movements.
● Form Validation: Validate input fields on the client-side before sending data to the
server.
● Interact with APIs: Fetch and manipulate data from servers or third-party services
using AJAX or Fetch API.
● Animation and Graphics: Create animations using libraries (e.g., GSAP) or HTML5
Canvas for 2D/3D graphics.
● Browser Storage: Store data locally using LocalStorage, SessionStorage, or Cookies.
● Server-Side Programming: Build backends with frameworks like [Link].
● Cross-Platform Applications: Develop desktop and mobile apps using frameworks
like Electron and React Native.
What javascript cannot do?
● Access Local Files Directly: Cannot read or write files on a user's system without user
input or APIs (e.g., FileReader).
● System-Level Operations: Cannot access hardware, install software, or perform
low-level system tasks.
● Threading and Multitasking: Operates in a single-threaded environment, with limited
support for multi-threading via Web Workers.
● Secure Content Access: Cannot bypass browser security measures to access restricted
domains or data.
● Native OS Features: Cannot directly access features like camera, GPS, or notifications
without APIs or permissions.
● Guaranteed Execution: If JavaScript is disabled in the user's browser, it won't execute.
● Complex Mathematical Computations: Handles intensive computations less efficiently
compared to low-level languages like C++.
Javascript syntax
● JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
● Scripts can be in the either <head> section or <body> section but it is normally
recommended to keep it within the <head> tags.
● Syntax:
<script language=”javascript” type="text/javascript">
…
…..
</script>
● The script tag takes two important attributes:
○ Language: This attribute specifies what scripting language you are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
○ Type: This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".
Javascript example
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
[Link] ("Hello World!")
</script>
</body>
</html>
In [Link]
[Link](“This is external implementation”)
Javascript fundamentals
● External file: same as in CSS
<script type="text/javascript" src="[Link]" ></script>
● Example:
In [Link]
<html>
<head>
<script type="text/javascript" src="[Link]">
</script>
</head>
</html>
In [Link]
[Link](“This is external implementation”)
Programming fundamentals
Javascript data types
● JavaScript allows us to work with three primitive data types:
● Numbers, eg. 123, 120.50, etc.
● Strings of text e.g. "This text string" etc.
● Boolean e.g. true or false.
● JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value.
● JavaScript supports a composite data type known as an object.
Javascript Variables
● Variables are Containers for Storing Data
● JavaScript Variables can be declared in 4 ways:
a. Automatically
b. Using var
c. Using let
d. Using const
● Example:
<script>
var price1 = 5;
const price2 = 6;
let total = price1 + price2;
[Link]("demo").innerHTML =
"The total is: " + total;
</script>
Javascript Variables
● There are some rules while declaring a JavaScript variable (also known as
identifiers).
○ Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
[Link] first letter we can use digits (0 to 9), for example: “value1”,
”_value123”.
○ We 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 variables are case sensitive, for example Name and name are
two different variables.
Javascript Variable scope
● The scope of a variable is the region of our program in which it is defined.
JavaScript variables have only two scopes.
1. Global Variables: A global variable has global scope which means it can be
defined anywhere in our JavaScript code.
- (Subtraction) Subtracts the second operand from the first Ex: A - B will give
2
-10
/ (Division)
4 Divide the numerator by the denominator Ex: B / A will give 2
% (Modulus)
5 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
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Comparison Operators
[Link]. Operator Description
1 = = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true.
Ex: (A == B) is not true.
2 != (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes
true.
Ex: (A != B) is true.
3 > (Greater than) Checks if the value of the left operand is greater than the value of the right the operand, if yes, then the
condition becomes true.
Ex: (A > B) is not true.
4 < (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition
becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then
to) the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the
condition becomes true.
Ex: (A <= B) is true.
logical Operators
[Link]. Operator Description
1 && (Logical AND) If both the operands are non-zero, then the condition becomes
true. Ex: (A && B) is true.
2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes
true. Ex: (A || B) is true.
3 ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the
Logical NOT operator will make it false.
Ex: ! (A && B) is false.
Bitwise Operators
[Link]. Operator
Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.
3 ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR
means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.
5 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to
multiplying it by 2, shifting two positions are equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
6 >> (Right Shift) Binary Right, Shift Operator. The left operand’s value is moved right by the number of bits specified
by the right operand.
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are always zero.
Ex: (A >>> 1) is 1.
Assignment Operators
[Link]. Operator
Description
1 = (Simple Assignment 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
2 += (Add and It adds the right operand to the left operand and assigns the result to the left operand.
Assignment) Ex: C += A is equivalent to C = C + A
3 −= (Subtract and It subtracts the right operand from the left operand and assigns the result to the left
Assignment) operand.
Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and It multiplies the right operand with the left operand and assigns the result to the left
Assignment) operand.
Ex: C *= A is equivalent to C = C * A
5 /= (Divide and It divides the left operand with the right operand and assigns the result to the left operand.
Assignment) Ex: C /= A is equivalent to C = C / A
6 %= (Modules and It takes modulus using two operands and assigns the result to the left operand.
Assignment) Ex: C %= A is equivalent to C = C % A
Conditional Operators
[Link]. Operator
Description
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
typeof Operators
Type String Returned by typeof
● The typeof operator is a unary operator that is
Number "number"
placed before its single operand, which can be of
any type. Its value is a string indicating the data String "string"
type of the operand.
● The typeof operator evaluates to "number", Boolean "boolean"
"string", or "boolean" if its operand is a number,
Object "object"
string, or boolean value and returns true or false
based on the evaluation.
Function "function"
● Here is a list of the return values for the typeof
Operator.:-> Undefined "undefined"
Null "object"
typeof Operators
● Example:
<html>
<body>
<script type="text/javascript">
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
[Link]("Result => ");
[Link](result);
[Link](linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
[Link]("Result => ");
[Link](result);
[Link](linebreak);
</script>
</body>
</html>
Javascript conditional statements
Javascript if statement
● It evaluates the content only if expression is true.
● The signature of JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
● Example
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
Javascript if else statement
● It evaluates the content whether condition is true of false.
● The syntax of JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
} else{
//content to be evaluated if condition is false
}
Javascript if else statement
● Example
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
} else{
[Link]("a is odd number");
}
</script>
Javascript if else if statement
● It evaluates the content only if expression is true from several expressions.
● The signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
} else if(expression2){
//content to be evaluated if expression2 is true
} else if(expression3){
//content to be evaluated if expression3 is true
} else{
//content to be evaluated if no expression is true
}
Javascript if else if statement
● Example:
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
} else if(a==15){
[Link]("a is equal to 15");
} else if(a==20){
[Link]("a is equal to 20");
} else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
Javascript switch statement
● The JavaScript switch statement is used to execute one code from multiple
expressions.
● The syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Javascript switch statement
<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";
}
[Link](result);
</script>
Javascript loops
Javascript loops
● The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
● There are four types of loops in JavaScript.
○ for loop
○ while loop
○ do-while loop
For loop
● The JavaScript for loop iterates the elements for the fixed number of
times.
● It should be used if number of iteration is known.
● The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
● Example
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
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.
● The syntax of while loop is given below.
while (condition)
{
code to be executed
}
● Example
<script>
var i=11;
while (i<=15) {
[Link](i + "<br/>");
i++; }
</script>
Do while loop
● The JavaScript do while loop iterates the elements for the infinite
number of times like while loop. But, code is executed at least once
whether condition is true or false.
● The syntax of do while loop is given below.
do{
code to be executed
}
while (condition);
● Example
<script>
var i=21;
do{ [Link](i + "<br/>");
i++;
}while (i<=25);
</script>
Jump statements
Break statement
● The break statement, which was briefly introduced with the switch statement, is used to
exit a loop early, breaking out of the enclosing curly braces.
● Example:
<script type="text/javascript">
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 20) {
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
</script>
continue statement
● The continue statement tells the interpreter to immediately start the next
iteration of the loop and skip the remaining code block.
● When a continue statement is encountered, the program flow moves to the
loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.
● Example:
<script type="text/javascript">
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skip rest of the loop body }
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
</script>
Dialog/Popup boxes
dialog/popup box
● JavaScript supports three important types of dialog boxes i.e, alert dialog box,
confirmation dialog box and prompt dialog box. These dialog boxes can be
used to raise an alert, or to get confirmation on any input or to have a kind of
input from the users.
Alert dialog 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.
● Syntax:
alert("sometext");
Alert dialog box
● Example:
<html>
<head>
<script type="text/javascript">
function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!"); }
</script>
</head>
<body>
<p>Click the following button to see the result: </p> <form>
<input type="button" value="Click Me" onclick="Warn();" /> </form>
</body>
</html>
Confirm dialog 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.
● Syntax:
confirm("sometext");
Confirm dialog box
● Example:
<html>
<head>
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?"); if( retVal == true ){
[Link] ("User wants to continue!"); return true;
}
else{
[Link] ("User does not want to continue!"); return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p> <form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
prompt dialog 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.
● Syntax:
prompt("sometext",”default_text”);
prompt dialog box
● Example:
<html>
<head>
<script type="text/javascript">
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal); }
</script>
</head>
<body>
<p>Click the following button to see the result: </p> <form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Javascript function
Javascript function
● A function is a group of reusable code which can be called anywhere in our
program.
● This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes.
● Functions allow a programmer to divide a big program into a number of small
and manageable functions.
● Like any other advanced programming language, JavaScript also supports all
the features necessary to write modular code using functions.
● JavaScript allows us to write our own functions as well.
Javascript function
● A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ( ).
● Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
● The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
● The code to be executed, by the function, is placed inside curly brackets: { }
● Syntax :
<script type="text/javascript">
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
</script>
Calling a function
● There is different ways of calling a function. They are:-
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Javascript number validation
● Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
Javascript Email Validation
● We can validate the email by the help of JavaScript.
● There are many criteria that need to be follow to validate the email id such as:
○ email id must contain the @ and . character
○ There must be at least one character before and after the @.
○ There must be at least two characters after . (dot).
● Example:
<html>
<body>
<script>
function validate_email ()
{
var x=[Link];
var atposition =[Link]("@");
var dotposition =[Link] (".");
if (atposition <1 || dotposition <atposition +6 || dotposition +3>=[Link]){
alert("Please enter a valid e-mail address!!" );
return false;
}
}
</script>
<body>
<form name="myform" method="post" onsubmit="return validate_email ();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register" >
</form>
</body>
</html>
Javascript Arrays
An Array is an object type designed for storing data collections.
const cars = [
"Saab",
"Volvo",
"BMW"
];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Javascript Arrays
Accessing Array Elements
cars[0] = "Opel";
Javascript Array Methods
pop()
• The pop() method removes the last element from an array:
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();//Output: Mango
push()
• The push() method adds a new element to an array (at the end):
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Kiwi");
[Link](fruits); \\output: Banana,Orange,Apple,Mango,Kiwi
Javascript Array Methods
shift()
• The shift() method removes the first array element and "shifts" all other elements to a
lower index.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
[Link](fruits); \\Orange,Apple,Mango
• The shift() method returns the value that was "shifted out".
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = [Link]();
[Link](fruit); \\output: Banana
Javascript Array Methods
unshift()
• The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Lemon");
[Link](fruits); \\output: Lemon,Banana,Orange,Apple,Mango
• The unshift() method returns the new array length.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruitLength = [Link]("Lemon");
[Link](fruitLength); \\output: 5
Javascript Array Methods
delete():
• Using delete() leaves undefined holes in the array.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
[Link](fruits[0]); \\output: undefined
concat():
• The concat() method creates a new array by merging (concatenating) existing arrays
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = [Link](myBoys);
[Link](myChildren) \\Output: Cecilie, Lone, Emil, Tobias, Linus
Javascript Array Methods
splice():
• The splice() method adds new items to an array.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](2, 0, "Lemon", "Kiwi");//output: Banana,Orange,Lemon,Kiwi,Apple,Mango
• The first parameter (2) defines the position where new elements should be added (spliced
in).
• The second parameter (0) defines how many elements should be removed. If the second
parameter was 1, the output would be: Banana,Orange,Lemon,Kiwi,Mango
• The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
Javascript Array Methods
Using splice() to Remove Elements
• With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](0, 1);
[Link](fruits); \\ouput: Orange,Apple,Mango
• The first parameter (0) defines the position where new elements should be added (spliced
in).
• The second parameter (1) defines how many elements should be removed.
• The rest of the parameters are omitted. No new elements will be added.
Javascript Array Methods
• slice():
• The slice() method slices out a piece of an array into a new array:
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = [Link](1);
[Link](citrus); \\ouput: Orange,Lemon,Apple,Mango
• The slice() method can take two arguments like slice(1, 3). The method then selects
elements from the start argument, and up to (but not including) the end argument.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = [Link](1, 3);
[Link](citrus); \\output: Orange,Lemon
Javascript Object
● An object in JavaScript is a data structure used to store related data collections.
● Objects are variables too. But objects can contain many values.
● It stores data as key-value pairs, where each key is a unique identifier for the associated
value.
● Objects are dynamic, which means the properties can be added, modified, or deleted at
runtime.
● Javascript is an Object Oriented Programming (OOP) language.
● Example:
○ Javascript variable:
let car = "Fiat";
○ Javascript object:
const car = {type:"Fiat", model:"500", color:"white"};
Javascript Object definition
● We can define javascript objects in following three ways:
○ Using Object Literal
○ Using the new keyword
○ Using an Object Constructor Function
Using Object Literal
● An object literal is a list of name:value pairs inside curly braces {}.
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
1. [Link](obj)
3. [Link](obj)
const obj1 = { a: 1 };
const obj2 = { b: 2 };
[Link](result);
Javascript Object Methods
5. [Link](obj)
[Link](user);
[Link]([Link]);
Javascript Object Methods
6. [Link](obj)
[Link](car);
8. [Link](property)
[Link]([Link]("city"));
Javascript Object Methods
9. [Link](proto)
[Link]([Link]);
[Link]([Link](10, 10));
[Link]([Link](NaN, NaN));
Document object model
● The Document Object Model (DOM) is a cross-platform and language-independent
interface that treats an HTML or XML document as a tree structure wherein each node is
an object representing a part of the document.
● The DOM represents a document with a logical [Link] branch of the tree ends in a
node, and each node contains objects.
● The principal standardization of the DOM was handled by the World Wide Web
Consortium (W3C), which last developed a recommendation in 2004.
● In HTML DOM (Document Object Model), every element is a node:[4]
○ A document is a document node.
○ All HTML elements are element nodes.
○ All HTML attributes are attribute nodes.
○ Text inserted into HTML elements are text nodes.
○ Comments are comment nodes.
Document object model
● DOM has a specific treemap structure like below:
Document object model
●
simple hierarchy of a few important objects in DOM
simple hierarchy of a few important objects in DOM
○ Window object − Top of the hierarchy. It is the outmost element of the object
hierarchy.
○ Document object − Each HTML document that gets loaded into a window becomes
a document object. The document contains the contents of the page.
○ Form object − Everything enclosed in the <form>...</form> tags sets the form
object.
○ Form control elements − The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and checkboxes.
Why is DOM required?
The DOM is essential because
● Dynamic Content Updates: Without reloading the page, the DOM allows content
updates (e.g., form validation, AJAX responses).
● User Interaction: It makes your webpage interactive (e.g., responding to button clicks,
form submissions).
● Flexibility: Developers can add, modify, or remove elements and styles in real-time.
● Cross-Platform Compatibility: It provides a standard way for scripts to interact with
web documents, ensuring browser compatibility.
Different DOM methods and Properties
● JavaScript - DOM Methods & Properties
● HTML DOM (Document Object Model) - GeeksforGeeks
Commonly Used DOM Methods and Properties
A. DOM Selection Methods
1. [Link]()
Syntax: Output:
Hello changes to Welcome
[Link]("id")
Example:
<p id="msg">Hello</p>
<script>
[Link]("msg").innerText = "Welcome";
</script>
Commonly Used DOM methods and Properties
2. [Link]()
Syntax:
[Link]("className")
Output:
First paragraph text becomes
Example: red
<p class="t">One</p>
<p class="t">Two</p>
<script>
[Link]("t")[0].[Link] = "red";
</script>
Commonly Used DOM methods and Properties
3. [Link]()
Syntax:
[Link]("tag")
Example: Output:
Heading text becomes Hi
<h1>Hello</h1>
<script>
[Link]("h1")[0].innerText = "Hi";
</script>
Commonly Used DOM methods and Properties
4. [Link]()
Syntax:
[Link]("selector")
Example: Output:
Text becomes bold
<p class="info">Text</p>
<script>
[Link](".info").[Link] = "bold";
</script>
Commonly Used DOM methods and Properties
5. [Link]()
Syntax:
[Link]("selector")
Example: Output:
Second paragraph text becomes
<p>A</p><p>B</p>
blue
<script>
[Link]("p")[1].[Link] = "blue";
</script>
Commonly Used DOM methods and Properties
B. DOM Content Properties
1. innerHTML
Syntax:
[Link] Output:
Text appears bold Hello
Example:
[Link]("msg").innerHTML = "<b>Hello</b>";
Commonly Used DOM methods and Properties
2. innerText
Syntax:
[Link]
Example: Output:
Text changes to World
[Link]("msg").innerText = "World";
Commonly Used DOM methods and Properties
3. textContent
Syntax:
[Link]
Example:
[Link]([Link]("msg").textContent);
Output (Console):
Displays element text
Commonly Used DOM methods and Properties
C. Style & Class Properties
1. style
Syntax:
[Link] = "value"
Example:
[Link]("msg").[Link] = "green";
Output:
Text color becomes green
Commonly Used DOM methods and Properties
2. classList
Syntax:
[Link]("className")
Example:
[Link]("box").[Link]("active");
Output:
Class active is added
Commonly Used DOM methods and Properties
D. Form & Attribute Properties
1. value
Syntax:
[Link]
Syntax:
[Link]("attr", "value")
Example:
[Link]("img").setAttribute("alt", "photo");
Output:
Attribute added
Commonly Used DOM methods and Properties
3. getAttribute()
Syntax:
[Link]("attr")
Example:
[Link]([Link]("img").getAttribute("alt"));
Output:(console)
photo
Commonly Used DOM methods and Properties
4. removeAttribute()
Syntax:
[Link]("attributename)
Example:
[Link]("btn").removeAttribute("value");
Output:
Button value is removed
Commonly Used DOM methods and Properties
E. Event Handling
1. addEventListener()
Syntax:
[Link]("event", function)
Example:
1. createElement()
Syntax:
[Link]("tag")
Example:
const p = [Link]("p");
Output:
[Link] = "New"; Paragraph created (not yet
visible)
Commonly Used DOM methods and Properties
2. appendChild()
Syntax:
[Link](child)
Example:
[Link](p);
Output:
Paragraph appears on page
Commonly Used DOM methods and Properties
3. removeChild()
Syntax:
[Link](child)
Example:
[Link](child);
Output:
Element removed
Commonly Used DOM methods and Properties
3. remove()
Syntax:
[Link]()
Example:
[Link]("msg").remove();
Output:
Element disappears
Commonly Used DOM methods and Properties
G. DOM Navigation Properties
1. parentElement
Syntax:
[Link]
Example:
[Link]([Link]);
Output:
Parent tag name printed
Commonly Used DOM methods and Properties
2. children
Syntax:
[Link]
Example:
[Link]([Link].l
Output:
Number of child elements
Commonly Used DOM methods and Properties
3. nextElementSibling
Syntax:
[Link]
Example:
[Link] = "red";
Output:
Next element turns red
Errors and Exception Handler
● Unused condition occur in the program is error.
● Error is also called exception.
● An exception signifies the presence of an abnormal condition which requires special
operable techniques.
● In programming terms, an exception is the anomalous code that breaks the normal flow
of the code. Such exceptions require specialized programming constructs for its
execution.
● In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them.
● It also enables to handle the flow control of the code/program.
● For handling the code, various handlers are used that process the exception and execute
the code.
● For example, the Division of a non-zero value with zero will result into infinity always,
and it is an exception. Thus, with the help of exception handling, it can be executed and
handled.
Errors and Exception Handler
● Types of errors:
a. Syntax Error: When a user makes a mistake in the pre-defined syntax of a
programming language, a syntax error may appear.
b. Runtime Error: When an error occurs during the execution of the program, such an
error is known as Runtime error. The codes which create runtime errors are known
as Exceptions. Thus, exception handlers are used for handling runtime errors.
c. Logical Error: An error which occurs when there is any logical mistake in the
program that may not produce the desired output, and may terminate abnormally.
Such an error is known as Logical error.
The Try…Catch statement
● A try…catch is a commonly used statement in various programming languages.
● Basically, it is used to handle the error-prone part of the code.
● It initially tests the code for all possible errors it may contain, then it implements actions
to tackle those errors (if occur).
● A good programming approach is to keep the complex code within the try…catch
statements.
● We can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.
● Try…..catch has two block
○ Try block🡪 code contain a block of code that is to be tested for error
○ Catch block 🡪 contain the code that is to be executed if an error occur.
The Try…Catch statement
● try{} statement:
○ Here, the code which needs possible error testing is kept within the try block.
○ In case any error occur, it passes to the catch{} block for taking suitable actions and
handle the error.
○ Otherwise, it executes the code written within.
● catch{} statement:
○ This block handles the error of the code by executing the set of statements written
within the block.
○ This block contains either the user-defined exception handler or the built-in
handler.
○ This block executes only when any error-prone code needs to be handled in the try
block.
○ Otherwise, the catch block is skipped.
The Try…Catch Statement
● Syntax:
<script type="text/javascript">
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception(e) occurs
[break;]
}
The Try…Catch statement
● Example:
<html>
<head>
<script type="text/javascript" >
function myFunc(){
var a = 100;
try {
dalert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + [Link] );
}}
</script>
</head>
<body>
<p>Click the following to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
The Throw statement
● A throw statement is used to raise an exception. It means when an abnormal condition
occurs, an exception is thrown using throw.
● The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will get
executed.
● Throw statements are used for throwing user-defined errors. User can define and throw
their own custom errors. When throw statement is executed, the statements present
after it will not execute. The control will directly pass to the catch block.
● Syntax:
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
The throw statement
● Example:
<html>
<head>
<script type="text/javascript" >
function myFunc(){
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}
else{
var c = a / b;
} }
catch ( e ) {
alert("Error: " + e );
} }
</script>
</head>
<body>
<p>Click the following to see the result: </p>
<form><input type="button" value="Click Me" onclick="myFunc();" /></form>
</body>
</html>
The Onerror() statement
● The Onerror event occur when a page has a script error.
● Onerror event occur when an image or document causes an error during loading.
● This doesn't mean that it is a browser error.
● The error event is fired on the window object whenever an exception occurs on the page.
● Synatx:
onerror=function_name()
function function_name(){
//error handling code
}
● The onerror event handler provides three pieces of information to identify the exact
nature of the error:
○ Error message: The same message that the browser would display for the given
error.
○ URL: The file in which the error occurred
○ Line number: The line number in the given URL that caused the error
The Onerror() statement
● Example:
<html>
<head>
<script type = "text/javascript">
[Link] = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form><input type = "button" value = "Click Me" onclick =
"myFunc();" /></form>
</body>
</html>
Important Questions:
1. Define DOM with hierarchy. Explain different properties and method of DOM with
example.
2. What is event handler? Explain about onclick event, onsubmit event, onmouseover and
onmouseout event.
3. What do you mean by event in javascript? Write a html code to create login form with
three input fields Name , Password and Email and write javascript code that will prevent
from submit and display suitable pop up message if either username or password field is
empty.
4. What is Javascript? Explain Window and String object in Javascript. Explain any five
string object methods with example.
5. Write a javascript code to validate with following conditions:
a. Name field should contain only alphabets
b. Email field should contain @ and .(dot)
c. Password should be at least 8 character long.
6. Define function with its type in javascript.