KEMBAR78
Module 3-1 | PDF | Document Object Model | Html Element
0% found this document useful (0 votes)
57 views53 pages

Module 3-1

This document provides an introduction to JavaScript, highlighting its dynamic nature and use in web development. It covers key concepts such as data types, variables, operators, and control statements, including if statements and loops. Additionally, it outlines the advantages of using JavaScript for creating interactive web pages and improving user experience.

Uploaded by

mbs.vinod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views53 pages

Module 3-1

This document provides an introduction to JavaScript, highlighting its dynamic nature and use in web development. It covers key concepts such as data types, variables, operators, and control statements, including if statements and loops. Additionally, it outlines the advantages of using JavaScript for creating interactive web pages and improving user experience.

Uploaded by

mbs.vinod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

‭Web Application and Development‬ ‭MMC205‬

‭Module 3‬

‭Introduction to JavaScript‬

J‭ avascript‬‭is‬‭a‬‭dynamic‬‭computer‬‭programming‬‭language.‬‭It‬‭is‬‭lightweight‬‭and‬‭most‬‭commonly‬‭used‬‭as‬
‭a‬‭part‬‭of‬‭web‬‭pages,‬‭whose‬‭implementations‬‭allow‬‭client-side‬‭scripts‬‭to‬‭interact‬‭with‬‭the‬‭user‬‭and‬‭make‬
‭dynamic pages. It is an interpreted programming language with object-oriented capabilities.‬

‭Advantages‬

‭●‬ L
‭ ess server interaction − You can validate user input before sending the page off to the server.‬
‭This saves server traffic, which means less load on your server.‬
‭●‬ I‭ mmediate feedback to the visitors − They don't have to wait for a page reload to see if they‬
‭have forgotten to enter something.‬
‭●‬ I‭ ncreased interactivity − You can create interfaces that react when the user hovers over them‬
‭with a mouse or activates them via the keyboard.‬
‭●‬ R
‭ icher interfaces − You can use JavaScript to include such items as drag-and-drop components‬
‭and sliders to give a Rich Interface to your site visitors.‬

‭Data Types‬

‭JavaScript allows you 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.‬

‭Trivial data types‬

‭null and undefined, each of which defines only a single value‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭1‬


‭Web Application and Development‬ ‭MMC205‬

‭composite data type object‬

‭Variables‬

‭ ariables are declared with the var keyword as follows. JavaScript is untyped language. This means‬
V
‭that a JavaScript variable can hold a value of any data type.‬

‭You can also declare multiple variables with the same var keyword as follows −‬

‭Storing a value in a variable is called variable initialization.‬

‭JavaScript Variable Scope‬


‭ he scope of a variable is the region of your program in which it is defined. JavaScript variables have‬
T
‭only two scopes.‬
‭●‬ G
‭ lobal Variables‬‭− A global variable has global scope‬‭which means it can be defined‬
‭anywhere in your JavaScript code.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭2‬


‭Web Application and Development‬ ‭MMC205‬

‭●‬ L
‭ ocal Variables‬‭− A local variable will be visible‬‭only within a function where it is defined.‬
‭Function parameters are always local to that function.‬
‭ ithin the body of a function, a local variable takes precedence over a global variable with the same‬
W
‭name.‬

‭This produces the following result −‬

‭Operators‬

‭What is an operator?‬
‭ et us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the‬
L
‭operator. JavaScript supports the following types of operators.‬
‭●‬ ‭Arithmetic Operators‬

‭●‬ ‭Comparison Operators‬

‭●‬ ‭Logical (or Relational) Operators‬

‭●‬ ‭Assignment Operators‬

‭●‬ ‭Conditional (or ternary) Operato‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭3‬


‭Web Application and Development‬ ‭MMC205‬

‭Types of Operators in JavaScript‬

‭JavaScript provides several categories of operators to perform various types of operations. These are:‬

‭1. Arithmetic Operators‬

‭These operators perform basic mathematical calculations.‬

‭Operator‬ ‭Description‬ ‭Example‬

‭+‬ ‭Addition‬ ‭4 + 5 = 9‬

‭-‬ ‭Subtraction‬ ‭9 - 4 = 5‬

‭*‬ ‭Multiplication‬ ‭3 * 4 = 12‬

‭/‬ ‭Division‬ ‭10 / 2 = 5‬

‭%‬ ‭Modulus (Remainder)‬ ‭7 % 3 = 1‬

‭++‬ ‭Increment (adds 1)‬ ‭x++ increases x by 1‬

‭--‬ ‭Decrement (subtracts 1)‬ ‭x-- decreases x by 1‬

‭Explanation:‬
‭Arithmetic operators are the most fundamental operators and allow for numerical calculations within‬
‭JavaScript programs. Increment and decrement operators are shorthand for increasing or decreasing a number‬
‭by one and are often used in loops.‬

‭2. Comparison Operators‬

‭These operators compare two values and return a Boolean result — either true or false.‬

‭Operator‬ ‭Description‬ ‭Example‬

‭==‬ ‭Equal to‬ ‭5 == '5' returns true‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭4‬


‭Web Application and Development‬ ‭MMC205‬

‭===‬ ‭Strict equal (value & type)‬ ‭5 === '5' returns false‬

‭!=‬ ‭Not equal to‬ ‭4 != 5 returns true‬

‭!==‬ ‭Strict not equal‬ ‭4 !== '4' returns true‬

‭>‬ ‭Greater than‬ ‭7 > 3 returns true‬

‭<‬ ‭Less than‬ ‭2 < 5 returns true‬

‭>=‬ ‭Greater than or equal to‬ ‭4 >= 4 returns true‬

‭<=‬ ‭Less than or equal to‬ ‭3 <= 5 returns true‬

‭Explanation:‬
‭Comparison operators are essential for making decisions in code, such as in if statements or loops. The strict‬
‭equality operators (‬‭===‬‭and‬‭!==‬‭) check both value‬‭and type, avoiding unexpected type coercion.‬

‭3. Logical (Relational) Operators‬

‭Logical operators combine multiple Boolean expressions and return Boolean values.‬

‭Operator‬ ‭Description‬ ‭Usage Example‬

‭&&‬ ‭Logical AND‬ ‭true && false returns false‬

‭||‬ ‭Logical OR‬ ‭true || false returns true‬

‭!‬ ‭Logical NOT (negation)‬ ‭!true returns false‬

‭Explanation:‬
‭Logical operators are used to evaluate complex conditions involving more than one criterion. For example,‬
‭checking if two conditions are both true (‬‭&&‬‭), if‬‭at least one is true (‬‭||‬‭), or negating a Boolean expression‬‭(‭!‬ ‬‭).‬

‭4. Assignment Operators‬

‭Assignment operators are used to assign values to variables, often combining arithmetic operations.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭5‬


‭Web Application and Development‬ ‭MMC205‬

‭Operator‬ ‭Description‬ ‭Example‬

‭=‬ ‭Simple assignment‬ ‭x = 5 assigns 5 to x‬

‭+=‬ ‭Add and assign‬ ‭x += 3 is equivalent to x = x + 3‬

‭-=‬ ‭Subtract and assign‬ ‭x -= 2 is equivalent to x = x - 2‬

‭*=‬ ‭Multiply and assign‬ ‭x *= 4 is equivalent to x = x * 4‬

‭/=‬ ‭Divide and assign‬ ‭x /= 2 is equivalent to x = x / 2‬

‭%=‬ ‭Modulus and assign‬ ‭x %= 3 is equivalent to x = x % 3‬

‭Explanation:‬
‭Assignment operators simplify expressions where a variable’s value needs to be updated based on its current‬
‭value. They make code shorter and more readable.‬

‭5. Conditional (Ternary) Operator‬

‭ he conditional operator is a compact form of an if-else statement that evaluates a condition and returns one of‬
T
‭two values based on whether the condition is true or false.‬

‭Syntax:‬
‭condition ? value_if_true : value_if_false‬

‭Explanation:‬
‭It is useful for concise conditional assignments or expressions where a simple decision is needed. It helps keep‬
‭the code clean and minimizes the number of lines, especially for straightforward conditions.‬

‭Summary‬

‭Operator Type‬ ‭Purpose‬ ‭Returns‬

‭Arithmetic Operators‬ ‭Perform mathematical calculations‬ ‭Numeric values‬

‭Comparison Operators‬ ‭Compare two values‬ ‭Boolean (true/false)‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭6‬


‭Web Application and Development‬ ‭MMC205‬

‭Logical Operators‬ ‭Combine Boolean expressions‬ ‭Boolean (true/false)‬

‭Assignment Operators‬ ‭Assign or update variable values‬ ‭Assigned value‬

‭Conditional (Ternary) Operator‬ ‭ hoose between two values based on‬ ‭One of two values‬
C
‭condition‬

‭Control Statements‬
‭It used to control the flow of execution within a program .Two types‬
‭1.‬ ‭Conditional‬
‭Decision Making Statement‬ ‭Loop Control Statement‬
‭1.‬‭if statement‬ ‭1.while‬
‭2.‬‭if .. else statement‬ ‭2. do – while‬
‭3.‬‭if – else – if statement‬ ‭3. for‬
‭4.‬‭switch‬ ‭4. for – in‬

‭2.‬ ‭Unconditional‬
‭1.‬ ‭break‬
‭2.‬ ‭continue‬
‭3.‬ ‭goto‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭7‬


‭Web Application and Development‬ ‭MMC205‬

‭if statement‬
‭ he if statement is the fundamental control statement that allows JavaScript to make decisions and‬
T
‭execute statements conditionally.‬
‭Syntax‬
‭The syntax for a basic if statement is as follows −‬

‭ ere‬ ‭a‬ ‭JavaScript‬ ‭expression‬ ‭is‬ ‭evaluated.‬ ‭If‬ ‭the‬ ‭resulting‬ ‭value‬ ‭is‬ ‭true,‬ ‭the‬ ‭given‬ ‭statement(s)‬ ‭are‬
H
‭executed.‬ ‭If‬ ‭the‬ ‭expression‬ ‭is‬ ‭false,‬‭then‬‭no‬‭statement‬‭would‬‭be‬‭not‬‭executed.‬‭Most‬‭of‬‭the‬‭times,‬‭you‬
‭will use comparison operators while making decisions.‬
‭Example‬
‭Try the following example to understand how the if statement works.‬

‭Output‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭8‬


‭Web Application and Development‬ ‭MMC205‬

‭if...else statement:‬

‭ he 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in‬
T
‭a more controlled way.‬
‭Syntax‬

‭ ere‬‭JavaScript‬‭expression‬‭is‬‭evaluated.‬‭If‬‭the‬‭resulting‬‭value‬‭is‬‭true,‬‭the‬‭given‬‭statement(s)‬‭in‬‭the‬‭‘if’‬
H
‭block,‬ ‭are‬ ‭executed.‬ ‭If‬ ‭the‬ ‭expression‬ ‭is‬ ‭false,‬ ‭then‬ ‭the‬ ‭given‬ ‭statement(s)‬ ‭in‬ ‭the‬ ‭else‬ ‭block‬ ‭are‬
‭executed.‬
‭Example‬
‭Try the following code to learn how to implement an if-else statement in JavaScript.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭9‬


‭Web Application and Development‬ ‭MMC205‬

‭Output‬

‭if...else if... statement‬

‭ he if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision‬
T
‭out of several conditions.‬
‭Syntax‬
‭The syntax of an if-else-if statement is as follows −‬

‭ here‬‭is‬‭nothing‬‭special‬‭about‬‭this‬‭code.‬‭It‬‭is‬‭just‬‭a‬‭series‬‭of‬‭if‬‭statements,‬‭where‬‭each‬‭if‬‭is‬‭a‬‭part‬‭of‬‭the‬
T
‭else‬‭clause‬‭of‬‭the‬‭previous‬‭statement.‬‭Statement(s)‬‭are‬‭executed‬‭based‬‭on‬‭the‬‭true‬‭condition,‬‭if‬‭none‬‭of‬
‭the conditions is true, then the else block is executed.‬
‭Example‬
‭Try the following code to learn how to implement an if-else-if statement in JavaScript.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭10‬


‭Web Application and Development‬ ‭MMC205‬

‭Output‬

‭Switch Statement‬
‭ he‬‭objective‬‭of‬‭a‬‭switch‬‭statement‬‭is‬‭to‬‭give‬‭an‬‭expression‬‭to‬‭evaluate‬‭and‬‭several‬‭different‬‭statements‬
T
‭to‬ ‭execute‬‭based‬‭on‬‭the‬‭value‬‭of‬‭the‬‭expression.‬‭The‬‭interpreter‬‭checks‬‭each‬‭case‬‭against‬‭the‬‭value‬‭of‬
‭the expression until a match is found. If nothing matches, a default condition will be used.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭11‬


‭Web Application and Development‬ ‭MMC205‬

‭ he break statements indicate the end of a particular case. If they were omitted, the interpreter would‬
T
‭continue executing each statement in each of the following cases.‬
‭We will explain break statement in‬‭Loop Control‬‭chapter.‬

‭Example‬
‭Try the following example to implement switch-case statement.‬

‭Output‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭12‬


‭Web Application and Development‬ ‭MMC205‬

‭Looping Statements‬

‭ hile‬‭writing‬‭a‬‭program,‬‭you‬‭may‬‭encounter‬‭a‬‭situation‬‭where‬‭you‬‭need‬‭to‬‭perform‬‭an‬‭action‬‭over‬‭and‬
W
‭over again. In such situations, you would need to write loop statements to reduce the number of lines.‬
‭The while Loop‬
‭ he‬ ‭most‬ ‭basic‬ ‭loop‬ ‭in‬ ‭JavaScript‬ ‭is‬ ‭the‬ ‭while‬ ‭loop‬ ‭which‬ ‭would‬ ‭be‬ ‭discussed‬ ‭in‬ ‭this‬ ‭chapter.‬ ‭The‬
T
‭purpose‬‭of‬‭a‬‭while‬‭loop‬‭is‬‭to‬‭execute‬‭a‬‭statement‬‭or‬‭code‬‭block‬‭repeatedly‬‭as‬‭long‬‭as‬‭an‬‭expression‬‭is‬
‭true. Once the expression becomes false, the loop terminates.‬
‭Syntax‬
‭The syntax of while loop in JavaScript is as follows −‬

‭Example‬
‭Try the following example to implement while loop.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭13‬


‭Web Application and Development‬ ‭MMC205‬

‭Output‬

‭The do...while Loop‬

‭ he‬ ‭do...while‬ ‭loop‬ ‭is‬‭similar‬‭to‬‭the‬‭while‬‭loop‬‭except‬‭that‬‭the‬‭condition‬‭check‬‭happens‬‭at‬‭the‬‭end‬‭of‬


T
‭the loop. This means that the loop will always be executed at least once, even if the condition is false.‬
‭Syntax‬
‭The syntax for do-while loop in JavaScript is as follows −‬

‭Example‬
‭Try the following example to learn how to implement a do-while loop in JavaScript.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭14‬


‭Web Application and Development‬ ‭MMC205‬

‭Output‬

‭For Loop‬

‭The 'for' loop is the most compact form of looping. It includes the following three important parts −‬
‭●‬ T‭ he‬ ‭loop‬ ‭initialization‬ ‭where‬ ‭we‬ ‭initialize‬ ‭our‬ ‭counter‬ ‭to‬ ‭a‬ ‭starting‬ ‭value.‬ ‭The‬ ‭initialization‬
‭statement is executed before the loop begins.‬
‭●‬ T‭ he‬‭test‬‭statement‬‭which‬‭will‬‭test‬‭if‬‭a‬‭given‬‭condition‬‭is‬‭true‬‭or‬‭not.‬‭If‬‭the‬‭condition‬‭is‬‭true,‬‭then‬
‭the code given inside the loop will be executed, otherwise the control will come out of the loop.‬
‭‬
● ‭The‬‭iteration‬‭statement‬‭where‬‭you‬‭can‬‭increase‬‭or‬‭decrease‬‭your‬‭counter.‬‭You‬
‭can put all the three parts in a single line separated by semicolons.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭15‬


‭Web Application and Development‬ ‭MMC205‬

‭Syntax‬
‭The syntax of for loop is JavaScript is as follows −‬

‭Example‬
‭Try the following example to learn how a for loop works in JavaScript.‬

‭Output‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭16‬


‭Web Application and Development‬ ‭MMC205‬

‭For – in‬

‭ he‬‭for...in‬‭loop‬‭is‬‭used‬‭to‬‭loop‬‭through‬‭an‬‭object's‬‭properties.‬‭As‬‭we‬‭have‬‭not‬‭discussed‬‭Objects‬‭yet,‬
T
‭you‬ ‭may‬ ‭not‬ ‭feel‬ ‭comfortable‬ ‭with‬ ‭this‬ ‭loop.‬ ‭But‬ ‭once‬ ‭you‬ ‭understand‬ ‭how‬ ‭objects‬ ‭behave‬ ‭in‬
‭JavaScript, you will find this loop very useful.‬
‭Syntax‬

I‭ n each iteration, one property from object is assigned to variablename and this loop continues till all‬
‭the properties of the object are exhausted.‬

‭Example‬
‭ ry‬ ‭the‬ ‭following‬ ‭example‬ ‭to‬ ‭implement‬ ‭‘for-in’‬ ‭loop.‬ ‭It‬ ‭prints‬ ‭the‬ ‭web‬
T
‭browser’s Navigator object.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭17‬


‭Web Application and Development‬ ‭MMC205‬

‭Output‬

‭Functions‬

‭ ‬‭function‬‭is‬‭a‬‭group‬‭of‬‭reusable‬‭code‬‭which‬‭can‬‭be‬‭called‬‭anywhere‬‭in‬‭your‬‭program.‬‭This‬‭eliminates‬
A
‭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.‬
‭Function Definition‬
‭ efore‬ ‭we‬ ‭use‬ ‭a‬ ‭function,‬ ‭we‬ ‭need‬ ‭to‬ ‭define‬ ‭it.‬ ‭The‬ ‭most‬ ‭common‬ ‭way‬ ‭to‬ ‭define‬ ‭a‬ ‭function‬ ‭in‬
B
‭JavaScript‬‭is‬‭by‬‭using‬‭the‬‭function‬‭keyword,‬‭followed‬‭by‬‭a‬‭unique‬‭function‬‭name,‬‭a‬‭list‬‭of‬‭parameters‬
‭(that might be empty), and a statement block surrounded by curly braces.‬

‭Syntax‬
‭The basic syntax is shown here.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭18‬


‭Web Application and Development‬ ‭MMC205‬

‭Example‬
‭Try the following example. It defines a function called sayHello that takes no parameters −‬

‭Calling a Function‬
‭ o invoke a function somewhere later in the script, you would simply need to write the name of that‬
T
‭function as shown in the following code.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭19‬


‭Web Application and Development‬ ‭MMC205‬

‭Output‬
‭Hello there!‬

‭Function Parameters‬
‭ ill‬‭now,‬‭we‬‭have‬‭seen‬‭functions‬‭without‬‭parameters.‬‭But‬‭there‬‭is‬‭a‬‭facility‬‭to‬‭pass‬‭different‬‭parameters‬
T
‭while‬ ‭calling‬ ‭a‬ ‭function.‬ ‭These‬ ‭passed‬ ‭parameters‬ ‭can‬ ‭be‬ ‭captured‬ ‭inside‬ ‭the‬ ‭function‬ ‭and‬ ‭any‬
‭manipulation‬‭can‬‭be‬‭done‬‭over‬‭those‬‭parameters.‬‭A‬‭function‬‭can‬‭take‬‭multiple‬‭parameters‬‭separated‬‭by‬
‭comma.‬
‭Example‬
‭Try the following example. We have modified our sayHello function here. Now it takes two parameters.‬

‭The return Statement‬


‭ JavaScript function can have an optional return statement. This is required if you want to return a value‬
A
‭from a function. This statement should be the last statement in a function.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭20‬


‭Web Application and Development‬ ‭MMC205‬

‭ or example, you can pass two numbers in a function and then you can expect the function to return‬
F
‭their multiplication in your calling program.‬
‭Example‬
‭ ry the following example. It defines a function that takes two parameters and concatenates them before‬
T
‭returning the resultant in the calling program.‬

‭Document Object Model (DOM):‬

‭DOM stands for Document Object Model. But what does that mean? Let's break it down.‬

‭ he‬‭Document‬‭part refers to the webpage you see in‬‭the browser. Specifically, the HTML Document which‬
T
‭handles the structure of the page's content. This includes the text, images, links, and other elements that make‬
‭up the page.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭21‬


‭Web Application and Development‬ ‭MMC205‬

‭ bject‬‭means the elements like images, headers, and paragraphs are treated like objects. Each object has its‬
O
‭properties (like id, class, style) and methods. Using these properties and methods, you can manipulate the‬
‭elements.‬

‭ he‬‭Model‬‭in DOM means it's a representation or copy‬‭of the HTML document as a hierarchical tree. This tree‬
T
‭includes all the elements. And it captures the parent-child relationships between them.‬

‭ he DOM is always identical to the HTML document. Browsers ensure that they are in sync. So if something‬
T
‭changes in the HTML, the DOM changes too, and vice versa.‬

‭A graphical representation of the HTML DOM tree‬

‭ t the top of the hierarchy is the Document object. It has only one child – the‬‭html‬‭element. The‬‭html‬‭element,‬
A
‭also known as the root element, has two children, the‬‭head‬‭and‬‭body‬‭elements. And each of them also‬‭have their‬
‭own children elements.‬

‭ he parent-child relationship between the elements is what allows you to traverse or move between and select‬
T
‭them. More on that later.‬

‭Accessing DOM Elements‬

‭JavaScript provides various DOM Selection methods to access elements:‬

‭Method‬ ‭Description‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭22‬


‭Web Application and Development‬ ‭MMC205‬

‭getElementById()‬ ‭Selects element by ID‬

‭getElementsByClassName()‬ ‭Selects elements by class name (HTMLCollection)‬

‭getElementsByTagName()‬ ‭Selects elements by tag name‬

‭querySelector()‬ ‭Selects first matching element using CSS selectors‬

‭querySelectorAll()‬ ‭Selects all matching elements (NodeList)‬

🔹 1.‬‭getElementById()‬

‭➤ Description:‬

‭●‬ ‭Returns the element object that has the specified‬‭id‬‭.‬

‭●‬ ‭This method is fast and commonly used for selecting unique elements.‬

‭➤ Syntax:‬
j‭avascript‬
‭document.getElementById("elementId");‬

‭➤ Example:‬
‭ tml‬
h
‭<p id="demo">Hello, World!</p>‬
‭<script>‬
‭let para = document.getElementById("demo");‬
‭para.style.color = "blue";‬
‭</script>‬

🔹 2.‬‭getElementsByClassName()‬

‭➤ Description:‬

‭●‬ ‭Returns a live HTMLCollection of all elements with the given class name.‬

‭●‬ ‭Elements can be accessed using index.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭23‬


‭Web Application and Development‬ ‭MMC205‬

‭➤ Syntax:‬
j‭avascript‬
‭document.getElementsByClassName("className");‬

‭➤ Example:‬
‭ tml‬
h
‭<p class="text">Paragraph 1</p>‬
‭<p class="text">Paragraph 2</p>‬
‭<script>‬
‭let items = document.getElementsByClassName("text");‬
‭items[0].style.fontWeight = "bold"; // Changes only the first paragraph‬
‭</script>‬

🔹 3.‬‭getElementsByTagName()‬

‭➤ Description:‬

‭●‬ ‭Returns a live HTMLCollection of elements with the specified tag name.‬

‭●‬ ‭Commonly used to manipulate groups of elements like‬‭<li>‬‭,‬‭<p>‬‭, etc.‬

‭➤ Syntax:‬
j‭avascript‬
‭document.getElementsByTagName("tagName");‬

‭➤ Example:‬
‭ tml‬
h
‭<ul>‬
‭<li>Item 1</li>‬
‭<li>Item 2</li>‬
‭</ul>‬
‭<script>‬
‭let listItems = document.getElementsByTagName("li");‬
‭listItems[1].style.color = "green"; // Changes color of second item‬
‭</script>‬

🔹 4.‬‭querySelector()‬

‭➤ Description:‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭24‬


‭Web Application and Development‬ ‭MMC205‬

‭●‬ ‭Returns the first element that matches a CSS selector.‬

‭●‬ ‭Supports complex selectors like‬‭.class‬‭,‬‭#id‬‭,‬‭tag[attr=value]‬‭.‬

‭➤ Syntax:‬
j‭avascript‬
‭document.querySelector("CSS_Selector");‬

‭➤ Example:‬
‭ tml‬
h
‭<div class="container">‬
‭<p>Hello</p>‬
‭<p>Hi</p>‬
‭</div>‬
‭<script>‬
‭let firstPara = document.querySelector(".container p");‬
‭firstPara.textContent = "Hello, Modified!";‬
‭</script>‬

🔹 5.‬‭querySelectorAll()‬

‭➤ Description:‬

‭●‬ ‭Returns a static NodeList of all elements matching the CSS selector.‬

‭●‬ ‭You can use methods like‬‭.forEach()‬‭to iterate.‬

‭➤ Syntax:‬
j‭avascript‬
‭document.querySelectorAll("CSS_Selector");‬

‭➤ Example:‬
‭ tml‬
h
‭<div class="box">Box 1</div>‬
‭<div class="box">Box 2</div>‬
‭<script>‬
‭let boxes = document.querySelectorAll(".box");‬
‭boxes.forEach(box => box.style.backgroundColor = "lightblue");‬
‭</script>‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭25‬


‭Web Application and Development‬ ‭MMC205‬

‭Manipulating DOM Elements (With Minimal Programming)‬

I‭ n modern web development, it is essential to interact with the elements of a webpage dynamically. JavaScript‬
‭allows us to modify the structure and behavior of a webpage after it has loaded, without needing to reload the‬
‭page. This is done using DOM manipulation.‬

‭Changing Content‬

‭You can change the content of an HTML element using the‬‭.innerHTML‬‭,‬‭.innerText‬‭, or‬‭.textContent‬‭properties.‬

‭●‬ ‭innerHTML‬‭: Allows you to insert or replace content‬‭with HTML tags (can include formatting).‬

‭●‬ ‭textContent‬‭: Inserts only text, treating any tags‬‭as plain text.‬

‭●‬ ‭innerText‬‭: Similar to‬‭textContent‬‭, but also respects‬‭CSS styles (like‬‭display: none‬‭).‬

🧪 Example:‬

j‭avascript‬
‭document.getElementById("para1").innerHTML = "Updated paragraph!";‬

✅ Use Case:‬

‭Useful when you want to dynamically update messages, error texts, or load new content via JavaScript.‬

‭Changing Attributes‬

‭Every HTML element has attributes (like‬‭src‬‭,‬‭href‬‭,‬‭alt‬‭,‬‭id‬‭,‬‭type‬‭, etc.). JavaScript allows you to:‬

‭●‬ ‭Access or change existing attributes.‬

‭●‬ ‭Add new attributes if they don't already exist.‬

🧪 Example:‬

j‭avascript‬
‭document.getElementById("link").href = "https://www.google.com";‬

✅ Use Case:‬

‭ his is useful when you want to redirect a user, update an image's‬‭src‬‭, or toggle form‬‭type‬‭dynamically (e.g.,‬
T
‭show/hide password).‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭26‬


‭Web Application and Development‬ ‭MMC205‬

‭Changing Styles‬

‭Using the‬‭.style‬‭property, you can apply or change‬‭inline CSS styles on any HTML element.‬

‭●‬ ‭JavaScript allows you to change styles instantly based on user input, events (click, hover), or conditions.‬

‭●‬ ‭Only inline styles are changed; it doesn’t affect CSS in‬‭<style>‬‭blocks or external stylesheets.‬

🧪 Example:‬

j‭avascript‬
‭document.getElementById("para1").style.color = "red";‬

✅ Use Case:‬

‭ elpful for creating dynamic visual effects, validating input fields, and enhancing user experience (UX)‬
H
‭without reloading the page.‬

‭Removing Elements‬

‭You can remove an element from the DOM completely using the‬‭.remove()‬‭method.‬

‭●‬ T
‭ his is useful when an element is no longer needed or should disappear after an action (e.g., dismissing‬
‭a notification).‬

🧪 Example:‬

j‭avascript‬
‭let element = document.getElementById("para1");‬
‭element.remove();‬

✅ Use Case:‬

‭Commonly used to delete elements on user action, like removing a task from a to-do list or closing a modal.‬

🔸 Summary Table‬

‭Manipulation Type‬ ‭Property/Method‬ ‭Description‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭27‬


‭Web Application and Development‬ ‭MMC205‬

‭Change Content‬ ‭.innerHTML‬‭/‬‭.textContent‬ ‭ eplaces element’s content‬


R
‭(with/without HTML)‬

‭Change Attribute‬ ‭.setAttribute()‬‭or direct assignment‬ ‭Changes values like‬‭src‬‭,‬‭href‬‭,‬‭alt‬

‭Change Style‬ ‭.style.propertyName‬ ‭Applies inline CSS styling‬

‭Remove Element‬ ‭.remove()‬ ‭ eletes the element from the‬


D
‭DOM tree‬

✨ Real-life Applications‬

‭●‬ ‭✅ Live content updates (e.g., news, notifications)‬

‭●‬ ‭✅ Form validation (changing color or showing messages)‬

‭●‬ ‭✅ Dynamic menus or tab systems‬

‭●‬ ‭✅ Interactive UI/UX elements (modals, sliders, etc.)‬

‭Event handling and event listeners‬

‭ n event is any action or occurrence that happens in the browser that the JavaScript can respond to. These‬
A
‭interactions can be triggered by the user, the browser, or other external sources.‬

J‭ avaScript is event-driven, meaning it can listen for events and respond to them by executing specific blocks of‬
‭code, known as event handlers.‬

🎯 Common Types of Events‬


‭Event Type‬ ‭Description‬ ‭Example‬

‭click‬ ‭When the user clicks an element‬ ‭Clicking a button‬

‭mouseover‬ ‭When the user hovers the mouse over an element‬ ‭Hovering over a menu‬

‭keydown‬ ‭When a key is pressed‬ ‭Typing in a text input‬

‭submit‬ ‭When a form is submitted‬ ‭ licking submit in a‬


C
‭contact form‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭28‬


‭Web Application and Development‬ ‭MMC205‬

‭load‬ ‭When the page or an image finishes loading‬ ‭ age or image fully‬
P
‭loaded‬

‭change‬ ‭When the value of an input changes‬ ‭ electing a different‬


S
‭option‬

‭dblclick‬ ‭When an element is double-clicked‬ ‭ ouble-clicking a list‬


D
‭item‬

‭scroll‬ ‭When the user scrolls the page or element‬ ‭ crolling through a blog‬
S
‭post‬

🛠️ How Events Work in JavaScript‬


‭When an event occurs (like a click), JavaScript can capture and respond to that event using:‬

‭●‬ ‭Event Handlers: Functions that run when a specific event happens.‬

‭●‬ ‭Event Listeners: A more flexible method to listen and respond to events.‬

✍️ Basic Event Handling Example‬


‭✅ HTML:‬
‭ tml‬
h
‭<button onclick="sayHello()">Click Me</button>‬

✅ JavaScript:‬

j‭avascript‬
‭function sayHello() {‬
‭alert("Hello, World!");‬
‭}‬

📌 Explanation:‬

‭●‬ ‭onclick="sayHello()"‬‭attaches an event handler to‬‭the button.‬

‭●‬ ‭When the button is clicked, the‬‭sayHello()‬‭function‬‭is executed.‬

🧠 ‬‭Why Events Are Important‬


‭ATME College of Engineering‬ ‭Department of MCA‬ ‭29‬


‭Web Application and Development‬ ‭MMC205‬

‭ vent handling is what makes websites interactive. Without it, webpages would be static and unresponsive to‬
E
‭user actions.‬

📌 ‬‭With event handling, you can:‬


‭●‬ ‭Create dynamic forms (validate input on the fly)‬

‭●‬ ‭Build interactive UI components (dropdowns, modals)‬

‭●‬ ‭React to real-time user activity (mouse movement, keystrokes)‬

‭●‬ ‭Control animations and transitions‬

‭●‬ ‭Track analytics (what users click, where they scroll, etc.)‬

‭Types of Events‬
‭ here are many different kinds of DOM events the browsers lets you listen to. The following are few of the‬
T
‭common ones.‬

‭Mouse events:‬

‭‬
● c‭ lick‬‭: when the element is clicked.‬
‭●‬ ‭dbclick‬‭: when the element is double clicked.‬
‭●‬ ‭mouseover‬‭: when the mouse pointer enters the element.‬
‭●‬ ‭mouseleave‬‭: when the mouse pointer leaves the element.‬
‭●‬ ‭mousedown‬‭: when the mouse is pressed down over an‬‭element.‬
‭●‬ ‭mouseup‬‭: when the mouse is released over an element.‬

‭Keyboard events:‬

‭ ‬ k‭ eydown‬‭: when a key on the keyboard is pressed down.‬



‭●‬ ‭keyup‬‭: when a key on the keyboard is released.‬
‭●‬ ‭keypress‬:‭ when a key is pressed and shows the actual‬‭key that was pressed. Note that this event is not‬
‭fired for all keys, especially non-printable keys.‬

‭Form events:‬

‭ ‬ s‭ ubmit‬‭: when a form is submitted.‬



‭●‬ ‭input‬‭: when the value of an input field changes.‬
‭●‬ ‭change‬:‭ when the value of a form element changes and‬‭loses focus.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭30‬


‭Web Application and Development‬ ‭MMC205‬

‭Window events:‬

‭‬
● l‭oad‬‭: when the browser finishes loading the page.‬
‭●‬ ‭unload‬‭: when the user leaves the page.‬
‭●‬ ‭resize‬‭: when the browser window is resized.‬
‭●‬ ‭scroll‬‭: when the user scrolls through the document.‬

‭You can see‬‭a comprehensive list of DOM events here‬‭.‬

‭Event Flow in JavaScript‬


‭ hen a JavaScript event occurs, the event is propagated or travels either from the target where the event‬
W
‭occurred to the outermost element in the DOM or vice versa.‬

‭ or example, let's say you click a button on a page. By clicking the button, you've also clicked its parent‬
F
‭element and any element the button is inside within the DOM hierarchy.‬

‭Creating and Modifying DOM Elements‬

‭ odern web applications often need to add, update, or remove elements dynamically on a webpage without‬
M
‭reloading. JavaScript provides a set of DOM manipulation methods to perform these tasks, enabling interactive‬
‭and responsive designs.‬

‭Creating Elements‬

✅ Theory:‬

‭ ou can create new HTML elements entirely through JavaScript using the‬‭document.createElement()‬‭method.‬
Y
‭This method creates a JavaScript object representing a new DOM element, which can then be customized and‬
‭inserted into the page.‬

🧪 Syntax:‬

‭Javascript‬

‭let newElement = document.createElement("tagName");‬

🧪 Example:‬

‭javascript‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭31‬


‭Web Application and Development‬ ‭MMC205‬

‭let newDiv = document.createElement("div");‬

‭newDiv.innerHTML = "This is a new div!";‬

‭document.body.appendChild(newDiv);‬

💡 Explanation:‬

‭●‬ ‭A new‬‭<div>‬‭is created.‬

‭●‬ ‭innerHTML‬‭sets its content.‬

‭●‬ ‭appendChild()‬‭adds it to the body.‬

✅ Use Case:‬

‭Used for dynamically adding components like:‬

‭●‬ ‭Cards‬

‭●‬ ‭Alerts‬

‭●‬ ‭User-generated content (comments, posts)‬

‭Appending Elements‬

✅ Theory:‬

‭Once an element is created, it must be added to the DOM. This is done by appending it to a parent element.‬

🧪 Common Methods:‬

‭Method‬ ‭Description‬

‭appendChild()‬ ‭Appends a single node as the last child‬

‭append()‬ ‭Can append multiple nodes and text (modern method)‬

🧪 Example:‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭32‬


‭Web Application and Development‬ ‭MMC205‬

‭javascript‬

‭let parent = document.getElementById("container");‬

‭let para = document.createElement("p");‬

‭para.textContent = "A new paragraph";‬

‭parent.appendChild(para);‬

💡 Explanation:‬

‭●‬ ‭A new‬‭<p>‬‭element is created.‬

‭●‬ ‭textContent‬‭is used for setting text.‬

‭●‬ ‭The paragraph is added inside the‬‭#container‬‭element.‬

‭Modifying Elements‬

✅ Theory:‬

‭DOM elements can be modified after being created or selected:‬

‭●‬ ‭Change text‬

‭●‬ ‭Change attributes‬

‭●‬ ‭Apply styles‬

‭●‬ ‭Add event listeners‬

🧪 Example:‬

‭javascript‬

‭para.textContent = "Updated paragraph text";‬

‭para.style.color = "green";‬

💡 Explanation:‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭33‬


‭Web Application and Development‬ ‭MMC205‬

‭●‬ ‭The content of the paragraph is updated.‬

‭●‬ ‭A new text color is applied using inline style.‬

✅ Use Case:‬

‭●‬ ‭Live editing of content‬

‭●‬ ‭Status updates (e.g., "Form Submitted")‬

‭●‬ ‭Visual changes (e.g., highlight, hide/show)‬

🔹 3.4 Removing Elements‬


‭✅ Theory:‬

‭To remove elements from the DOM, JavaScript provides multiple ways:‬

🔹 Method 1:‬‭.remove()‬

‭Removes the element directly.‬

‭javascript‬

‭let removeMe = document.getElementById("deleteThis");‬

‭removeMe.remove();‬

🔹 Method 2:‬‭parent.removeChild(child)‬

‭Removes a child element from its parent.‬

‭javascript‬

‭let parent = document.getElementById("container");‬

‭let child = document.getElementById("deleteThis");‬

‭parent.removeChild(child);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭34‬


‭Web Application and Development‬ ‭MMC205‬

💡 Use Case:‬

‭●‬ ‭Deleting messages‬

‭●‬ ‭Removing completed tasks‬

‭●‬ ‭Hiding expired banners or notifications‬

✨ Real-World Applications‬

‭●‬ ‭🗂️ Building dynamic content like blog posts, cards, and lists‬

‭●‬ ‭✅ Form and input feedback (show/hide messages)‬

‭●‬ ‭🧾 User interactions like deleting rows, items, or alerts‬

‭●‬ ‭📦 Building Single Page Applications (SPA)‬

‭Definition‬

‭ orm validation refers to the process of ensuring that the data submitted through a web form meets predefined‬
F
‭criteria before it is processed or sent to the server. Validation helps maintain data integrity and enhances the‬
‭overall user experience by providing immediate feedback.‬

‭Importance of Form Validation‬

‭●‬ ‭Ensures required fields are not left blank.‬

‭●‬ ‭Verifies that user input follows the expected format.‬

‭●‬ ‭Confirms that data values fall within acceptable ranges.‬

‭●‬ ‭Provides real-time feedback to users.‬

‭●‬ ‭Reduces server-side processing by catching errors early.‬

‭Types of Validation‬

‭1.‬ ‭Required Field Validation: Ensures that mandatory fields are filled.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭35‬


‭Web Application and Development‬ ‭MMC205‬

‭2.‬ ‭Format Validation: Checks that input matches specific patterns (e.g., email addresses, phone numbers).‬

‭3.‬ ‭Length Validation: Ensures the input has an appropriate number of characters.‬

‭4.‬ ‭Range Validation: Verifies that numeric inputs fall within a specified range.‬

‭5.‬ C
‭ onsistency Validation: Ensures related fields have consistent values (e.g., password and confirm‬
‭password).‬

‭JavaScript Methods Commonly Used in Validation‬

‭Method/Property‬ ‭Purpose‬

‭.value‬ ‭Retrieves the current value of an input field.‬

‭.trim()‬ ‭Removes whitespace from both ends of a string.‬

‭.length‬ ‭Returns the number of characters in a string.‬

‭Regular Expressions (‬‭RegExp‬‭)‬ ‭Used to test if input matches a specific pattern.‬

‭Basic Example‬
‭javascript‬

‭function validateForm() {‬

‭const username = document.getElementById("username").value;‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭36‬


‭Web Application and Development‬ ‭MMC205‬

‭if (username.trim() === "") {‬

‭alert("Username is required.");‬

‭return false;‬

‭}‬

‭return true;‬

‭}‬

‭ his function checks if the username field is empty after removing any leading or trailing spaces. If it is empty,‬
T
‭it alerts the user and prevents the form submission.‬

‭Common Validation Scenarios‬

‭Field‬ ‭Validation Criterion‬

‭Name‬ ‭Must not be empty‬

‭Email‬ ‭Must follow a valid email format‬

‭Password‬ ‭Minimum length requirement‬

‭Age‬ ‭Numeric value within specified range‬

‭Confirm Password‬ ‭Must match the original password‬

‭Client-Side vs Server-Side Validation‬

‭Validation Type‬ ‭Location‬ ‭Advantages‬ ‭Considerations‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭37‬


‭Web Application and Development‬ ‭MMC205‬

‭Client-side‬ ‭ rowser‬
B ‭ rovides immediate feedback;‬
P ‭ an be bypassed, so not‬
C
‭(JavaScript)‬ ‭reduces load on server‬ ‭fully secure‬

‭Server-side‬ ‭Server‬ ‭ nsures data security and‬


E ‭ equires additional server‬
R
‭integrity‬ ‭resources‬

I‭ t is recommended to implement both client-side and server-side validations to ensure data correctness and‬
‭application security.‬

‭Summary‬

J‭ avaScript form validation is essential for verifying user input before submission. It enhances data quality,‬
‭provides user guidance, and optimizes application performance. Validation typically involves checking for‬
‭required inputs, correct formats, acceptable value ranges, and consistency between related fields.‬

‭Asynchronous JavaScript: Callbacks, Promises, and Async/Await‬

‭Introduction‬

‭ ne of the most powerful features of the JavaScript language is the ability to handle asynchronous operations.‬
O
‭Asynchronous programming allows developers to perform tasks like fetching data from a server or reading a‬
‭file without blocking the main execution thread. This ensures that applications remain responsive and efficient,‬
‭providing a smoother user experience and better performance.‬

‭Basics of Asynchronous Programming‬

I‭ n programming, operations can be either synchronous or asynchronous. Understanding the difference between‬
‭these two types is crucial for effective programming.‬

‭Synchronous Programming‬

‭ ynchronous programming blocks the execution of subsequent code until the current operation completes. This‬
S
‭means that each task is performed one after the other, waiting for the previous one to finish.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭38‬


‭Web Application and Development‬ ‭MMC205‬

‭ onsider a scenario where you need to book a flight, reserve a hotel room, and rent a car for a trip. In a‬
C
‭synchronous world, you would call each service one by one, waiting on hold until each booking is confirmed‬
‭before moving to the next. This approach can be problematic in certain situations, particularly when dealing‬
‭with tasks that take a significant amount of time to complete.‬

‭ good example is when a synchronous program performs a task that requires waiting for a response from a‬
A
‭remote server. The program will be stuck waiting for the response and cannot do anything else until the‬
‭response is returned. This is known as‬‭blocking‬‭, and‬‭it can lead to the application appearing unresponsive or‬
‭“frozen” to the user.‬

‭synchronous operations‬

‭Asynchronous Programming‬

I‭ n contrast, asynchronous programming allows the execution of subsequent code to proceed independently‬
‭while waiting for the current operation to complete.‬

‭ sing the same scenario where you need to book a flight, reserve a hotel room, and rent a car for a trip, in an‬
U
‭asynchronous world, you could call all three services simultaneously. While waiting for each service to confirm‬
‭your booking, you can continue with other trip preparations, making the overall process faster and more‬
‭efficient.‬

‭ synchronous programming allows a program to continue working on other tasks while waiting for external‬
A
‭events, such as network requests, to occur. For example, while a program retrieves data from a remote server, it‬
‭can continue to execute other tasks such as responding to user inputs. This greatly improves the performance‬
‭and responsiveness of a program.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭39‬


‭Web Application and Development‬ ‭MMC205‬

‭asynchronous operations‬

‭Handling Asynchronous Operations‬

I‭ n JavaScript, asynchronous programming can be achieved through a variety of techniques. In this article, we‬
‭are going to cover ways in which you can do this.‬

‭Using Callbacks‬

‭ allbacks are one of the oldest and most widely used methods for handling asynchronous operations in‬
C
‭JavaScript. A callback function is simply a function that is passed as an argument to another function and is‬
‭executed after the completion of a task.‬

‭// Declare function‬

‭function‬‭fetchData(‬‭callback‬‭) {‬

‭setTimeout‬‭(() => {‬

‭const‬‭data = {‬‭name‬‭:‬‭"John"‬‭,‬‭age‬‭:‬‭24‬‭};‬

‭callback(data);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭40‬


‭Web Application and Development‬ ‭MMC205‬

‭},‬‭3000‬‭);‬

‭}‬

‭// Execute function with a callback‬

‭fetchData(‬‭function‬‭(‬‭data‬‭) {‬

‭console.log(data);‬

‭});‬

‭console.log(‬‭"Data is being fetched..."‬‭);‬

‭In this example:‬

‭‬ W
● ‭ e declare a function named‬‭fetchData‬‭that takes a‬‭callback function as an argument.‬
‭●‬ ‭Inside‬‭fetchData‬‭, the‬‭setTimeout‬‭function is used‬‭to simulate an asynchronous operation by‬
‭delaying the execution of a callback function for 3 seconds.‬
‭●‬ ‭After the 3-second delay, the callback function passed to‬‭fetchData‬‭is invoked with a mock data‬
‭object as its argument.‬
‭●‬ ‭The callback function passed to‬‭fetchData‬‭is an anonymous‬‭function that logs the received data‬
‭object to the console.‬
‭●‬ ‭Output: Initially, a message “Data is being fetched…” is logged to the console. After 3 seconds, the‬
‭mock data object is fetched, and the callback function is executed, logging the data object to the‬
‭console.‬

‭ allbacks are powerful because they allow us to continue with other tasks while waiting for asynchronous‬
C
‭operations to complete. However, they can lead to callback hell, a situation where multiple nested callbacks‬
‭make the code difficult to read and maintain.‬

‭getData(‬‭function‬‭(‬‭data1‬‭) {‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭41‬


‭Web Application and Development‬ ‭MMC205‬

‭processData1(data1,‬‭function‬‭(‭d‬ ata2‬‭) {‬

‭processData2(data2,‬‭function‬‭(‬‭data3‬‭) {‬

‭processData3(data3,‬‭function‬‭(‬‭data4‬‭) {‬

‭// and so on...‬

‭});‬

‭});‬

‭});‬

‭});‬

I‭ n this example, each asynchronous operation depends on the result of the previous one, leading to deeply‬
‭nested callbacks. As more operations are added, the code becomes increasingly difficult to manage, often‬
‭resulting in bugs and decreased readability.‬

‭ espite their drawbacks, callbacks are still widely used, especially in older codebases and libraries.‬
D
‭Understanding how to use callbacks effectively is essential for any JavaScript developer.‬

‭Using Promises‬

‭ romises provide a more elegant way to handle asynchronous operations compared to callbacks. A Promise‬
P
‭represents a value that may be available now, in the future, or never. Promises have three states: Pending,‬
‭Fulfilled, and Rejected.‬

‭function‬‭fetchData() {‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭42‬


‭Web Application and Development‬ ‭MMC205‬

‭return‬‭new‬‭Promise((‬‭resolve, reject‬‭) => {‬

‭setTimeout‬‭(() => {‬

‭const‬‭data = {‬‭name‬‭:‬‭"John"‬‭,‬‭age‬‭:‬‭24‬‭};‬

‭resolve(data);‬

‭},‬‭3000‬‭);‬

‭});‬

‭}‬

‭fetchData().then(console.log).catch(console.error);‬

I‭ n this example, the‬‭fetchData‬‭function returns a‬‭Promise. Inside the Promise constructor, an asynchronous‬
‭operation is simulated using‬‭setTimeout‬‭. Once the‬‭operation is complete, the‬‭resolve‬‭function is called‬‭with the‬
‭fetched data.‬

‭ romises allow for chaining using the‬‭then‬‭method,‬‭making it easy to perform sequential asynchronous‬
P
‭operations. Additionally, error handling is simplified with the‬‭catch‬‭method, which handles any errors that‬
‭occur during the execution of the Promise chain.‬

‭Async/Await: Simplifying Asynchronous Code‬

‭ sync/Await is a powerful feature in JavaScript that simplifies asynchronous programming by providing a‬


A
‭more synchronous-looking syntax. While it builds on top of Promises, it offers a more intuitive way to handle‬
‭asynchronous operations without directly dealing with Promise chains.‬

‭function‬‭fetchData() {‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭43‬


‭Web Application and Development‬ ‭MMC205‬

‭return‬‭new‬‭Promise((‬‭resolve, reject‬‭) => {‬

‭setTimeout‬‭(() => {‬

‭const‬‭data = {‬‭name‬‭:‬‭"John"‬‭,‬‭age‬‭:‬‭24‬‭};‬

‭resolve(data);‬

‭},‬‭3000‬‭);‬

‭});‬

‭}‬

‭async‬‭function‬‭getData() {‬

‭try‬‭{‬

‭const‬‭data =‬‭await‬‭fetchData();‬

‭console.log(data);‬

‭}‬‭catch‬‭(error) {‬

‭console.error(error);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭44‬


‭Web Application and Development‬ ‭MMC205‬

‭}‬

‭}‬

‭getData();‬

‭ ere, the‬‭fetchData‬‭function returns a Promise, as‬‭it did before. However, instead of chaining‬‭.then()‬‭and‬
H
‭.catch()‬‭methods, the‬‭getData‬‭function is defined‬‭as an‬‭async‬‭function. Inside‬‭getData‬‭, the‬‭await‬‭keyword‬‭is‬
‭used to pause the execution until the‬‭fetchData‬‭Promise‬‭resolves, making the asynchronous code flow appear‬
‭synchronous.‬

‭ sing Async/Await simplifies error handling with traditional‬‭try‬‭/‭c‬ atch‬‭blocks, providing a more natural way to‬
U
‭handle errors in asynchronous code. Overall, Async/Await makes asynchronous programming in JavaScript‬
‭more readable and maintainable by allowing developers to write asynchronous code that looks and behaves like‬
‭synchronous code.‬

‭Practical Applications of Asynchronous JavaScript‬

‭ synchronous JavaScript is essential for creating responsive and efficient applications. Here are some practical‬
A
‭applications where asynchronous operations play a crucial role:‬

‭1.Fetching Data from APIs‬

‭ pplications often need to retrieve data from external APIs. Asynchronous operations allow the application to‬
A
‭continue running while waiting for the data to be fetched.‬

‭async‬‭function‬‭fetchUserData() {‬

‭try‬‭{‬

‭const‬‭response =‬‭await‬‭fetch(‬‭'https://api.example.com/user'‬‭);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭45‬


‭Web Application and Development‬ ‭MMC205‬

‭const‬‭data =‬‭await‬‭response.json();‬

‭console.log(data);‬

‭}‬‭catch‬‭(error) {‬

‭console.error(‬‭'Error fetching user data:'‬‭,‬‭error);‬

‭}‬

‭}‬

‭fetchUserData();‬

I‭ n this example, the‬‭fetch‬‭API is used to retrieve‬‭user data. The‬‭await‬‭keyword ensures the code waits‬‭for the‬
‭response before proceeding, without blocking the main thread.‬

‭2.File Operations‬

‭ hen working with files, such as reading or writing to the file system, asynchronous operations are essential to‬
W
‭prevent the main thread from freezing.‬

‭const‬‭fs =‬‭require‬‭(‬‭'fs'‬‭);‬

‭fs.readFile(‬‭'file.txt'‬‭,‬‭'utf8'‬‭, (‬‭err, data‬‭) => {‬

‭if‬‭(err) {‬

‭console.error(‬‭'Error reading file:'‬‭, err);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭46‬


‭Web Application and Development‬ ‭MMC205‬

‭return‬‭;‬

‭}‬

‭console.log(‬‭'File contents:'‬‭, data);‬

‭});‬

‭console.log(‬‭'This message will be printed first'‬‭);‬

I‭ n this example, when‬‭fs.readFile()‬‭is called, Node.js‬‭initiates the file read operation but doesn't wait for it to‬
‭complete. Instead, it registers the provided callback function and immediately continues executing the next line,‬
‭which logs the message‬‭'This message will be printed‬‭first'‬‭. When the file read operation completes, Node.js‬
‭places the callback function in the event queue, and the event loop eventually dequeues and executes it on the‬
‭main thread, logging the file contents or an error message.‬

‭ y using asynchronous programming for file operations, the main execution thread remains responsive and can‬
B
‭handle other tasks while waiting for the file operation to complete.‬

‭3.Timers‬

J‭ avaScript provides the‬‭setTimeout‬‭and‬‭setInterval‬‭functions for scheduling code execution after a specified‬


‭delay or at regular intervals, respectively. These functions are asynchronous, meaning they don't block the main‬
‭execution thread while waiting for the specified time to elapse.‬

‭// Scheduling a recurring execution every second‬

‭const‬‭intervalId =‬‭setInterval‬‭(() => {‬

‭console.log(‬‭'This message will be displayed every‬‭second'‬‭);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭47‬


‭Web Application and Development‬ ‭MMC205‬

‭},‬‭1000‬‭);‬

‭// After 5 seconds, stop the recurring execution‬

‭setTimeout‬‭(() => {‬

‭clearInterval‬‭(intervalId);‬

‭console.log(‬‭'Interval cleared'‬‭);‬

‭},‬‭5000‬‭);‬

I‭ n this example, we store the identifier returned by‬‭setInterval‬‭in the‬‭intervalId‬‭variable. After 5‬‭seconds (using‬
‭setTimeout‬‭), we call‬‭clearInterval(intervalId)‬‭, which‬‭stops the recurring execution scheduled by‬‭setInterval‬‭.‬

‭ he‬‭clearInterval‬‭function is useful when you want‬‭to stop a recurring task based on certain conditions, such as‬
T
‭user interactions, state changes, or timers. Without‬‭clearInterval‬‭, the recurring execution would continue‬
‭indefinitely unless the page is reloaded or the script is terminated.‬

‭4.Animations‬

‭ reating smooth animations is another important use case for asynchronous JavaScript. The‬
C
‭requestAnimationFrame‬‭function is designed specifically‬‭for this purpose. It tells the browser to update an‬
‭animation before the next repaint, ensuring optimal performance and efficient use of system resources.‬

‭const‬‭element = document.getElementById(‬‭'myElement'‬‭);‬

‭let‬‭position =‬‭0‬‭;‬

‭function‬‭animateElement() {‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭48‬


‭Web Application and Development‬ ‭MMC205‬

‭position +=‬‭10‬‭;‬‭// Update the position‬

‭element.style.left =‬‭̀‬‭${position}‬‭px`‬‭;‬‭// Move the‬‭element‬

‭// Request the next animation frame‬

‭if‬‭(position <‬‭500‬‭) {‬

‭requestAnimationFrame(animateElement); }}‬

‭// Start the animation‬

‭requestAnimationFrame(animateElement);‬

I‭ n this example, the‬‭animateElement‬‭function is recursively‬‭called using‬‭requestAnimationFrame‬‭until the‬


‭desired position is reached. The browser handles these function calls asynchronously, ensuring that the‬
‭animation runs smoothly without blocking the main execution thread, ensuring a seamless user experience in‬
‭web applications.‬

‭5.Event Handling‬

‭ vent handling in the browser is inherently asynchronous, as events are triggered by user interactions or other‬
E
‭external factors.‬

‭const‬‭button = document.getElementById(‬‭'myButton'‬‭);‬

‭button.addEventListener(‬‭'click'‬‭, () => {‬

‭console.log(‬‭'Button clicked!'‬‭);‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭49‬


‭Web Application and Development‬ ‭MMC205‬

‭});‬

‭console.log(‬‭'This message will be displayed first'‬‭);‬

I‭ n this example, when the script runs, it logs the message‬‭'This message will be displayed first'‬‭to‬‭the console‬
‭immediately. However, the event handler function (‬‭()‬‭=> { console.log('Button clicked!'); }‬‭) is not executed‬
‭until the user actually clicks the button.‬

‭ hen the user clicks the button, the browser generates a‬‭click‬‭event and adds it to the event queue. The‬‭event‬
W
‭loop detects the event in the queue and executes the registered event handler function, which logs the message‬
‭'Button clicked!'‬‭to the console.‬

‭ his asynchronous nature of event handling ensures that the JavaScript code doesn’t block the main execution‬
T
‭thread while waiting for user interactions or other external events. The browser can continue to update the UI,‬
‭parse HTML, execute other scripts, and perform other tasks while waiting for events to occur.‬

‭Conclusion‬

‭ he practical applications discussed are indeed among the most important and widely-used cases where‬
T
‭asynchronous JavaScript is employed. However, these examples do not represent an exhaustive list.‬

I‭ t is crucial to recognize that asynchronous programming is a widespread concept that finds applications in‬
‭numerous other scenarios within the constantly evolving field of web development and beyond. As new‬
‭technologies and use cases emerge, the significance of asynchronous programming in JavaScript is likely to‬
‭continue increasing, ensuring efficient, responsive, and scalable applications across various domains.‬

‭AJAX (Asynchronous JavaScript and XML)‬

‭Overview‬

‭ JAX is a web development technique that enables web pages to communicate with a server asynchronously‬
A
‭without requiring a full page reload. By exchanging small amounts of data in the background, AJAX facilitates‬
‭dynamic and responsive web applications.‬

‭This approach revolutionized web interaction by enabling:‬

‭●‬ ‭Partial page updates instead of complete reloads.‬

‭●‬ ‭Faster response times and reduced server load.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭50‬


‭Web Application and Development‬ ‭MMC205‬

‭●‬ ‭Improved user experience through seamless content updates.‬

‭Working Principle of AJAX‬

‭ JAX relies on creating an HTTP request from the client-side JavaScript to the server, which processes the‬
A
‭request and returns data in formats such as JSON, XML, HTML, or plain text. The client-side JavaScript then‬
‭uses the received data to update the web page dynamically.‬

‭This interaction happens behind the scenes, so users can continue interacting with the page without interruption.‬

‭Evolution Beyond XML‬

‭ lthough AJAX originally stood for Asynchronous JavaScript and XML, the use of XML has declined over‬
A
‭time, with JSON becoming the preferred data format due to its lightweight nature and ease of integration with‬
‭JavaScript.‬

‭Fetch API‬

‭Introduction‬

‭ he Fetch API is a modern interface for making HTTP requests from the browser. It simplifies the process of‬
T
‭fetching resources asynchronously and replacing older technologies like XMLHttpRequest.‬

‭Features and Advantages‬

‭●‬ ‭Provides a cleaner, promise-based syntax for handling requests.‬

‭●‬ ‭Supports various HTTP methods like GET, POST, PUT, DELETE.‬

‭●‬ ‭Handles response streams and allows parsing of JSON, text, and other data formats.‬

‭●‬ ‭Improves readability and maintainability of asynchronous network code.‬

‭●‬ ‭Supports chaining and composability through Promises.‬

‭Browser Support and Usage‬

‭ he Fetch API is widely supported in modern browsers, though some older browsers require polyfills. Its‬
T
‭adoption encourages writing modular and declarative asynchronous code that aligns with modern JavaScript‬
‭development practices.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭51‬


‭Web Application and Development‬ ‭MMC205‬

‭Introduction to JavaScript Libraries (with Focus on jQuery)‬

‭Purpose of JavaScript Libraries‬

J‭ avaScript libraries are collections of pre-written JavaScript code designed to simplify common tasks, such as‬
‭DOM manipulation, event handling, animation, and AJAX calls.‬

‭These libraries provide:‬

‭●‬ ‭Cross-browser compatibility.‬

‭●‬ ‭Simplified syntax and abstraction.‬

‭●‬ ‭Enhanced developer productivity.‬

‭●‬ ‭Reusable components and utilities.‬

‭Overview of jQuery‬

j‭Query is one of the most popular and widely used JavaScript libraries that emerged to address challenges like‬
‭inconsistent browser implementations and verbose DOM manipulation code.‬

‭Key features of jQuery include:‬

‭●‬ ‭Simplified and chainable syntax for DOM selection and manipulation.‬

‭●‬ ‭Robust event handling mechanisms.‬

‭●‬ ‭Built-in AJAX methods for asynchronous server communication.‬

‭●‬ ‭Animation effects and utilities.‬

‭●‬ ‭Extensive plugin ecosystem to extend functionality.‬

‭Impact of jQuery‬

j‭Query dramatically increased the speed of web development by abstracting browser inconsistencies and‬
‭reducing the amount of code developers needed to write for common tasks.‬

‭ espite the rise of modern frameworks like React, Angular, and Vue, jQuery remains relevant in legacy‬
D
‭projects and simple use cases.‬

‭Summary Table‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭52‬


‭Web Application and Development‬ ‭MMC205‬

‭Concept‬ ‭Description‬

‭Asynchronous JavaScript‬ ‭ rogramming style allowing non-blocking operations to‬


P
‭improve performance and UX.‬

‭Callbacks‬ ‭ unctions passed as arguments to handle asynchronous results,‬


F
‭prone to nesting issues.‬

‭Promises‬ ‭ bjects representing future completion or failure of async‬


O
‭operations, enabling chaining and better error handling.‬

‭Async/Await‬ ‭ yntax to write asynchronous code that looks synchronous,‬


S
‭enhancing readability.‬

‭AJAX‬ ‭ echnique to update web pages asynchronously without full‬


T
‭reloads using HTTP requests.‬

‭Fetch API‬ ‭ odern, promise-based API for making HTTP requests,‬


M
‭replacing XMLHttpRequest.‬

‭JavaScript Libraries‬ ‭ re-built collections of code to simplify JavaScript‬


P
‭programming tasks.‬

‭jQuery‬ ‭ opular JS library for easier DOM manipulation, event‬


P
‭handling, and AJAX with cross-browser support.‬

‭ATME College of Engineering‬ ‭Department of MCA‬ ‭53‬

You might also like