JavaScript

Introduction
Introduction

JavaScript is one of the most widely used programming languages in the world, mainly for building interactive and dynamic websites. It is often called “The Language of the Web” because it runs inside the browser, allowing developers to add behavior to static HTML pages.

History of JavaScript
Developed By Brendan Eich
When & Where In 1995 at Netscape Communications
Original purpose To add interactivity and dynamic features to web pages.
Initial Names Originally called Mocha, then changed to LiveScript, and finally named as JavaScript.
Why Java in the name? Netscape partnered with Sun Microsystems to market JavaScript as a companion to Java. Java was popular at the time, so the name helped in promotion. But JavaScript and Java are completely different languages.
Early Development (1996-1999)
In 1996 Microsoft created JScript (their own JavaScript version) for Internet Explorer.
Problem Different browsers had incompatible implementations → Developers had to write separate code for each browser.
In 1997 ECMA International standardized JavaScript as ECMAScript (ES).
Stagnation Period (2000-2008)
Browsers implemented JavaScript differently, leading to the term “Cross-browser incompatibility”.
Development slowed due to lack of agreement among browser vendors.
JavaScript was mainly used for small form validations and simple animations.
Revival and Modern Era (2009 to At Present)
2009 – ECMAScript 5 (ES5)
  • strict Mode ("use strict";) introduced
  • JSON support
  • Array methods like forEach(), map(), filter()
2015 – ECMAScript 6 (ES6 / ES2015)((Biggest update in JavaScript history)
  • let and const are introduced
  • Arrow Functions
  • Template Literals
  • Classes and Modules
  • Promises
  • Default Parameters...
ES2016 includes() method, exponentiation operator **
ES2017 async/await
ES2018 Rest/Spread in objects, asynchronous iteration
ES2019 flat(), flapmap()
ES2020 Optional Chaining ?., Nullish Coalescing ??
ES2021–2024 Logical Assignment Operators, Top-level await, Array.prototype.at(), and more.
  • Lightweight and fast

  • Object-based (supports OOP features)

  • Interpreted language (no need for compilation)

  • Event-driven (responds to user events)

  • Cross-platform compatible

  • First-class functions (functions can be assigned to variables, passed as arguments)

  1. Form validation
  2. Creating interactive UI/UX
  3. DOM manipulation
  4. Games and animations
  5. AJAX (Asynchronous Web Requests)
  6. Backend development (using Node.js)
Role of JavaScript in Modern Web Development
Client-Side Scripting
  • Runs in the browser, reducing server load
  • Makes pages interactive (e.g., sliders, animations, dynamic forms)
Server-Side Development
  • With Node.js (2009), JavaScript can run on servers
  • Used for building APIs, microservices, and real-time apps (e.g., chat apps)
Full Stack Development
  • JavaScript is the only language that can run both on client and server
  • Popular stacks: MERN (MongoDB, Express, React, Node.js), MEAN (MongoDB, Express, Angular, Node.js)
Mobile App Development
  • Frameworks like React Native and Ionic allow building cross-platform mobile apps.
Desktop Applications Electron.js enables building cross-platform desktop apps (e.g., VS Code, Slack).
Game Development HTML5 Canvas + JavaScript for browser games. Libraries like Phaser.js make game creation easier.

JavaScript can be added to an HTML document in three main ways:

Inline JavaScript

Code is written directly inside an HTML tag using the onclick, onmouseover, or other event attributes. Used for small, quick scripts.

Syntax:

<button onclick=”alert(‘Hello!’)”>Click Me</button>

Code is written inside <script> tags within the HTML file, usually inside the <head> or <body> section.  Suitable for page-specific scripts.

Syntax:

<script>
document.write("Welcome to JavaScript!");
</script>

Code is placed in a separate .js file and linked to the HTML page using the <script src="filename.js"></script> tag. Helps in code reusability and better organization.

JavaScript can run in two main places:

Browser : 
For web pages, DOM manipulation, and interactive UI.
Server / Local Machine (via Node.js)
For backend apps, scripts, and tools.
2025 Update:
Modern browsers now fully support ES2023+ features, and Node.js LTS 22+ is stable with built-in test runner,
fetch API, and top-level await.

Using the Browser Console:

Purpose: Quick testing, debugging, and DOM inspection.

  1. Open your preferred browser (Chrome, Edge, or Firefox). 
    Press:
    Windows/Linux: Ctrl + Shift + J
    Mac: Cmd + Option + J
  2. This opens Developer ToolsConsole tab, then type
    console.log("Hello, JavaScript 2025!");
    const numbers = [1, 2, 3];
    console.log(numbers.at(-1)); // Last element
    document.body.style.background = "lightblue";

Purpose: Professional code editing with syntax highlighting, extensions, and integrated terminal.

Steps:

  1. Download from https://code.visualstudio.com

  2. Install with Add to PATH option checked.

  3. Open VS Code → FileOpen Folder → select your project folder.

Recommended Extensions (2025)

  • ESLint – Linting and error detection.

  • Prettier – Code formatting.

  • JavaScript (ES6+) Snippets – Faster coding.

  • Live Server – Auto-refresh browser during development.

  • Code Spell Checker – Avoid typos.

No. of ways

There are 3 ways to implement JavaScript in HTML.

  1. inline
  2. internal
  3. external
Inline JavaScript Example

Inline JavaScript means writing JavaScript code directly inside an HTML element’s event attribute (e.g., onclick, onmouseover, onchange).

Syntax:

<tag event=”JavaScript Code”></tag>

In the above syntax…

     tag: Any HTML tag like h1, p, button,...
     event: An HTML event like onclick, mouseover,...
     JavaScript Code: JavaScript statements inside quotes.

Example:

<!DOCTYPE html>
<html>
    <head>
         <title>Inline Script Example</title>
    </head>
    <body>
          <button onclick="alert('Hello, welcome to Inline JavaScript!')">Click Me</button>
    </body>
</html>

Advantages:

  • It is fast and easy for small scripts

  • No extra file needed

Disadvantages:

  • Hard to maintain for large projects

  • Mixing HTML and JS reduces code readability

Internal JavaScript Example

Internal JavaScript means writing JavaScript code inside the <script> tag in the same HTML file. Usually placed inside <head> or <body> sections.

Syntax:

<script>
     JavaScript code here
</script>

Example:

<!DOCTYPE html>
<html>
<head>
<title>Internal Script Example</title>
<script>
function wish() {
alert("Hello from Internal JavaScript!");
}
</script>
</head>
<body>
<button onclick="wish()">Click Me</button>
</body>
</html>

You can also place the script tag before closing body tag.

Placing <script> before the closing </body> improves page loading speed because HTML loads before JS.

Advantages:

  • Keeps JavaScript separate from HTML content

  • Good for medium-size scripts

Disadvantages:

  • Still mixes structure (HTML) and behavior (JS) in one file

External JavaScript Example

External JavaScript means writing JavaScript code in a separate .js file and linking it to the HTML file using the <script> tag’s src attribute.

Syntax:

<script src=”example.js”></script>

Example

index.html

<!DOCTYPE html>
<html>
<head>
<title>External Script Example</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="wish()">Click Me</button>
</body>
</html>

script.js

function wish() {
alert("Hello from External JavaScript!");
}

Advantages:

  • JavaScript code is completely separated from HTML → better readability and maintainability

  • Same .js file can be used in multiple web pages (reusability)

  • Browser caches the .js file → faster loading after first visit

Disadvantages:

  • Requires an extra HTTP request to load the file (slightly slower initial load)

Comparison Table
FeatureInline ScriptInternal ScriptExternal Script
LocationInside HTML elementInside <script> in HTMLSeparate .js file
Best ForSmall code, quick eventsMedium scriptsLarge, reusable scripts
MaintainabilityLowMediumHigh
ReusabilityNoNoYes
Page SpeedFast for very small codeMediumCan be cached (fast after first load)

In JavaScript, comments are notes written inside the code that the JavaScript engine ignores during execution. They are used to 

write description/explain the code
write heading of the program.
hide statements from execution.

There are 3 types of comments
1. Single line comments -- //
2. Multi line comments -- /* */
3. Documentation comments -- /** */
Introduction

Variables are names of memory allocations those holds data. Think of it a labeled box in a medical store that contains tablets in side the box.

  1. Can contain letters, digits, underscores, $.
  2. Cannot start with a digit.
  3. Case-sensitive (Name and name are different).
  4. Avoid using reserved keywords (e.g., var, let, if)

In JavaScript there are 3 ways to declare variables.

KeywordScopeReassignableHoistingBest Use
varFunctionYesYesLegacy code
letBlockYesNoWhen value changes
constBlockNoNoWhen value should not change

Examples:

var city = "Nellore";   // Old way
let age = 34; // Modern, preferred
const PI = 3.14159; // Constant value

 

Datatypes

A datatype specifies which type of value we are using in the program. There are two types of datatypes known as…

  1. Primitive Types
    1. String → Text ("Hello", 'World')

    2. Number → Numeric values (10, 3.14)

    3. Boolean → Logical values (true, false)

    4. Undefined → Variable declared but not assigned

    5. Null → Explicitly no value

    6. Symbol → Unique value for object property keys

    7. BigInt → Very large integers

Examples:
let name = "Alice"; // String
let score = 95; // Number
let isPassed = true; // Boolean
let value; // Undefined
let emptyValue = null; // Null
let uniqueID = Symbol(); // Symbol
let bigNumber = 12345678901234567890n; // BigInt
  1. Non-Primitive Types
    1. Object → Collection of key-value pairs

    2. Array → Ordered list of values

    3. Function → Block of reusable code

Examples:
let student = { name: "Bob", age: 20 }; // Object
let fruits = ["Apple", "Banana", "Cherry"]; // Array
function greet() { console.log("Hello!"); } // Function

To see output and debug code.

console.log("Hello World!");                  // General output
console.warn("Warning!"); // Yellow warning
console.error("Error!"); // Red error
console.table(["HTML", "CSS", "JavaScript"]); // Tabular view

What is an operator:

An operator is nothing but a symbol that performs a specific task on a given one or more operands.
Types of Operators in JavaScript
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. String Operators
6. Ternary/Conditional Operator
7. Bitwise Operators
8. Other Operators
Arithmetic Operators
Arithmetic Operators: 
Used to perform basic arithmetic operations like addition, subtraction, multiplication... , 
and the operators are ...
OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division10 / 25
%Modulus (remainder)10 % 31
**Exponentiation2 ** 38
++Incrementx++Adds 1
--Decrementx--Subtracts 1
Assignment Operators:
Used to assign values to variables.
Operator Example Equivalent to
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
**= x **= 3 x = x ** 3
Rational/Comparison Operators:
Used to assign values to variables.
OperatorExampleEquivalent to
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
**=x **= 3x = x ** 3
Logical Operators:
Logical Operators are used to compare more than 2 values or to combine more than 1 relational operators. 
These operators return either true or false. And the Operators are...
Operator Description Example Result
&& Logical AND true && false false
|| Logical OR true || false true
! Logical NOT !true false
String Operator:
+ is also called concatenation operator that is used to add strings.
for example 
'Hello' + 'Suresh'
HelloSuresh
Ternary Operator:
It is a shortcut of an if-else statement. 
It tests the given condition, if it is true, executes statement1; otherwise, statement2.
Syntax:
condition ? valueIfTrue : valueIfFalse

Bitwise operators work on numbers at the binary level. JavaScript converts numbers into 32-bit signed integers for bitwise operations, performs the operation, and then converts the result back to a regular JavaScript number.

These operators are often used in low-level programming, optimization, encryption, and graphics programming.

The Bitwise operators are …

OperatorSymbolDescriptionExample
AND&Returns 1 only if both bits are 1.5 & 3 → 1
OR``Returns 1 if at least one bit is 1.
XOR (Exclusive OR)^Returns 1 if bits are different.5 ^ 3 → 6
NOT (Bitwise Negation)~Inverts bits (turns 0 to 1, 1 to 0).~5 → -6
Left Shift<<Shifts bits to the left, filling with 0.5 << 1 → 10
Right Shift (Signed)>>Shifts bits to the right, keeping sign bit.-5 >> 1 → -3
Zero-Fill Right Shift>>>Shifts right, filling with 0 (ignores sign).-5 >>> 1 → 2147483645

 

Examples:

Let’s take two numbers:
a = 5 → (0101 in binary)
b = 3 → (0011 in binary)

0101 (5) & 0011 (3) = 0001 (1)
console.log(5 & 3); // Output: 1

0101 (5) | 0011 (3) = 0111 (7)
console.log(5 | 3); // Output: 7

0101 (5) ^ 0011 (3) = 0110 (6)
console.log(5 ^ 3); // Output: 6

0101 (5)
~ ----
= 1010 (-6 in decimal, because of 2’s complement)

0101 (5) << 1 = 1010 (10)
console.log(5 << 1); // Output: 10

0101 (5) >> 1 = 0010 (2)
console.log(5 >> 1); // Output: 2

-5 in 32-bit: 11111111111111111111111111111011 >>> 1
= 01111111111111111111111111111101 (2147483645)
typeof Operator:
The typeof operator in JavaScript is used to determine the data type of a given value or variable.
It returns a string that specifies the type.

Syntax: typeof (operand)

Example:
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (special case/quirk in JS)
console.log(typeof [1, 2, 3]); // "object" (arrays are objects)
console.log(typeof {name: "JS"}); // "object"
console.log(typeof function(){}); // "function"

 

Introduction

JavaScript provides a rich set of built-in methods to work with strings. A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`) for template literals.

You can declare a string in any one of the following way…

  1. let s1 = ‘Suresh’
  2. let s2 = “Suresh”
  3. let s3 = Suresh`
Method Description
length Returns the number of characters in the string.
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns Unicode of the character at the specified index.
concat(str1, str2) Joins two or more strings.
includes(substring) Checks if the string contains the specified substring.
startsWith(substring) Checks if the string starts with the given substring.
endsWith(substring) Checks if the string ends with the given substring.
Search and Index methhods:
indexOf(substring) Returns the first index of the substring, or -1 if not found.
lastIndexOf(substring) Returns the last index of the substring.
search(regex) Searches using regular expression.
Manipulation Methods
slice(start, end) Extracts part of a string from start to end (not including end).
substring(start, end) Similar to slice, but doesn't accept negative values.
substr(start, length) Extracts a substring starting from index with given length. (Deprecated)
replace(search, replacement) Replaces matched substring.
replaceAll(search, replacement) Replaces all matched substrings.
split(separator) Splits the string into an array using separator.
Case Conversion Methods
toUpperCase() Converts the string to uppercase.
toLowerCase() Converts the string to lowercase
Trim and Pad Methods
trim() Removes whitespace from both ends.
trimStart() / trimEnd() Removes whitespace from start/end
padStart(length, char) Pads the string from end.
What is Math in JavaScript?

In JavaScript, Math is a built-in object that provides a collection of mathematical constants and functions — like rounding numbers, calculating powers, generating random numbers, and working with trigonometry.

Constant Description
Math.PI The value of π (3.14159...)
Math.E Euler's number (2.718...)
Math.SQRT2 Square root of 2
Math.SQRT1_2 Square root of 1/2
Math.LN2 Natural logarithm of 2
Math.LN10 Natural logarithm of 10
Math.LOG2E Base 2 logarithm of E
Math.LOG10E Base 10 logarithm of E
Function Description
Math.round(x) Rounds x to the nearest integer
Math.floor(x) Rounds x down to nearest integer
Math.ceil(x) Rounds x up to nearest integer
Math.trunc(x) Removes the decimal part (truncates)
Math.pow(x, y) Returns x raised to the power y
Math.sqrt(x) Returns the square root of x
Math.cbrt(x) Returns the cube root of x
Math.abs(x) Absolute (positive) value of x
Math.sign(x) Returns the sign of x (-1, 0, 1)
Math.min(x1, x2, ...) Returns the smallest number
Math.max(x1, x2, ...) Returns the largest number
Math.random() Returns a random number between 0 and 1
Math.log(x) Natural log (base e) of x
Math.log2(x) Base 2 logarithm of x
Math.log10(x) Base 10 logarithm of x
Math.exp(x) Returns e raised to the power of x
Math.sin(x) Sine of x (in radians)
Math.cos(x) Cosine of x (in radians)
Math.tan(x) Tangent of x (in radians)
Math.asin(x) Arcsine of x
Math.acos(x) Arccosine of x
Math.atan(x) Arctangent of x
Math.atan2(y, x) Arctangent of y/x, considering quadrant
Definition

In JavaScript, an array is a special variable used to store multiple values in a single variable, known as an object.

We can store different data type elements as a single block.

There are two ways to declare an array variable.

  1. let numbers = [1,2,3,4,5]
  2. let number = new Array(5)

for example:

<script>
    let a = [1,2,3,4,5];
    document.writeln( typeof(a));
    document.write(‘<br>’+a)
    let b = new Array(5)
    document.write(‘<br>’+typeof(b))
    document.write(‘<br>’+b)
</script>
Output:
object
1,2,3,4,5
object
,,,,
Introduction

JavaScript provides a rich set of built-in methods to work with strings. A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`) for template literals.

You can declare a string in any one of the following way…

  1. let s1 = ‘Suresh’
  2. let s2 = “Suresh”
  3. let s3 = Suresh`
Method Description
length Returns the number of characters in the string.
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns Unicode of the character at the specified index.
concat(str1, str2) Joins two or more strings.
includes(substring) Checks if the string contains the specified substring.
startsWith(substring) Checks if the string starts with the given substring.
endsWith(substring) Checks if the string ends with the given substring.
Search and Index methhods:
indexOf(substring) Returns the first index of the substring, or -1 if not found.
lastIndexOf(substring) Returns the last index of the substring.
search(regex) Searches using regular expression.
Manipulation Methods
slice(start, end) Extracts part of a string from start to end (not including end).
substring(start, end) Similar to slice, but doesn't accept negative values.
substr(start, length) Extracts a substring starting from index with given length. (Deprecated)
replace(search, replacement) Replaces matched substring.
replaceAll(search, replacement) Replaces all matched substrings.
split(separator) Splits the string into an array using separator.
Case Conversion Methods
toUpperCase() Converts the string to uppercase.
toLowerCase() Converts the string to lowercase
Trim and Pad Methods
trim() Removes whitespace from both ends.
trimStart() / trimEnd() Removes whitespace from start/end
padStart(length, char) Pads the string from end.

In JavaScript, working with strings is very common. Traditionally, strings were written using single quotes (‘ ‘) or double quotes (” “). However, these had limitations when:

  • Adding variables inside strings

  • Creating multi-line strings

To solve this, Template Literals were introduced in ES6 (ECMAScript 2015).

What are Template Literals?

  • Template literals are strings enclosed by backticks (`) instead of single (') or double (") quotes.

  • They provide a more powerful and flexible way to handle strings.

Features of Template Literals

Multi-line Strings: 
With normal strings, writing multi-line text required escape characters (\n). Template literals make it easy.
String Interpolation (Embedding Expressions): 
The ${} syntax allows embedding variables and expressions directly inside a string.
Nesting Template Literals:
You can use template literals inside another template literal.
Tagged Templates (Advanced): 
A tagged template allows you to parse template literals with a function.

JavaScript is a loosely typed (or dynamically typed) language, which means variables are not bound to a specific type. The value assigned to a variable determines its type. When working with different data types, JavaScript automatically or manually converts them into other types. This process is called Type Conversion.

There are two types of type conversion in JavaScript:

  1. Implicit Type Conversion (Type Coercion)

  2. Explicit Type Conversion (Type Casting)

Implicit Type Conversion (Type Coercion)

JavaScript automatically converts one data type to another during operations.

Rules of Type Coercion:

  • If you use + with a string and a number, the number is converted to a string (concatenation).

  • Other arithmetic operators (-, *, /, %) convert values to numbers.

  • Boolean values are converted to 1 (true) or 0 (false) when used in arithmetic operations.

Example:

// String + Number → String
let result1 = "10" + 5;
console.log(result1); // "105" (number 5 is coerced into string)

// Number + Boolean → Number
let result2 = 10 + true;
console.log(result2); // 11 (true → 1)

// String * Number → Number
let result3 = "5" * 2;
console.log(result3); // 10 (string "5" → number 5)// String - Number → Number
let result4 = "20" - 5;
console.log(result4); // 15

// String + String → String
let result5 = "Hello " + "World";
console.log(result5); // "Hello World"

Sometimes, implicit conversion may lead to unexpected results:

console.log("5" + 1); // "51" (string concatenation)
console.log("5" - 1); // 4 (string converted to number)

Explicit Type Conversion (Type Casting)

Here, developers manually convert values from one type to another using JavaScript methods.

To Number

  • Number(value)

  • parseInt(value) → Converts to integer

  • parseFloat(value) → Converts to floating-point

console.log(Number("123")); // 123
console.log(parseInt("123.45")); // 123
console.log(parseFloat("123.45")); // 123.45
console.log(Number(true)); // 1
console.log(Number(false)); // 0

To String

  • String(value)

  • value.toString()

console.log(String(100)); // "100"
console.log((100).toString()); // "100"
console.log(String(true)); // "true"

To Boolean

  • Boolean(value)

Falsy values (converted to false):
     0, "", null, undefined, NaN, false

Truthy values (converted to true):
     All other vlaues.

console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("JS")); // true

Comparison: Implicit vs Explicit Conversion

FeatureImplicit Conversion (Coercion)Explicit Conversion (Casting)
Who does it?JavaScript (automatic)Developer (manual)
ControlLess predictableFully controlled
Example"5" + 1 → "51"Number("5") + 1 → 6
RiskMay lead to unexpected resultsSafe and intentional
 
Event Handling

What is an event?

An event in JavaScript is an action/occurrence/task that happens in the browser, which the program can respond like…

  • A user clicks a button (onclick)

  • A key is pressed (onkeypress)

  • A web page finishes loading (onload)

  • A mouse is moved (onmousemove)

Events can make web pages interactive and dynamic.

What is event handling?

Event Handling refers to the process of capturing events (like clicks, keystrokes, mouse movement) and executing a function (event handler) when the event occurs.

  • Event: The action (click, load, keypress, etc.)
  • Event Handler: The JavaScript function that runs when the event occurs.

        <button onclick=”alert(‘Button Clicked!’)”>Click Me</button>

In the above statement, onclick is an event and alert() is an Event Handler.

There are several ways to handle events in JavaScript; they are

     1. Inline Event Handling (HTML Attribute) 
2. Internal Event Handling (Using DOM properties)
3. External Event Handling (Using addEventListener)
Inline Event Handling (HTML Attribute)

     You directly attach an event inside the HTML element using event attributes.

Example:

<button onclick="sayWish()">Click Me</button>
<script>
function sayWish() {
alert("Hello! Welcome to Event Handling...");
}
</script>
Internal Event Handling (Using DOM properties)
You assign an event handler to an element’s event property in JavaScript.

Example:

<<button id="myBtn">Click Me</button>
<script>
document.getElementById("myBtn").onclick = function() {
alert("Button was clicked!");
};
</script>
External Event Handling (Using addEventListener)

The most modern and flexible way.

  • You can attach multiple handlers to a single event.

  • Keeps HTML and JavaScript separate.

Example:

<<button id="myBtn">Click Me</button>
<script>
let button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Hello! You used addEventListener.");
});
</script>
EventDescription
onclickTriggered when an element is clicked
ondblclickTriggered when an element is double-clicked
onmouseoverMouse pointer moves over an element
onmouseoutMouse pointer leaves an element
onmousemoveMouse moves inside the element
onkeydownWhen a key is pressed down
onkeyupWhen a key is released
onkeypressWhen a key is pressed and released
onchangeWhen input value changes (like dropdown/textbox)
onsubmitWhen a form is submitted
onloadWhen a web page is fully loaded
onresizeWhen browser window is resized

When an event occurs, the browser creates an event object that contains details about the event (e.g., mouse position, key pressed).

<button id="demo">Click Me</button>

 

<script>
document.getElementById(“demo”).addEventListener(“click”, function(event) {
alert(“You clicked at X: ” + event.clientX + “, Y: ” + event.clientY);
});
</script>

What is event bubbling?

Event Bubbling is a mechanism in the DOM where an event starts from the target element (the element that was actually interacted with) and then bubbles up to its parent elements, then to their parents, and so on, until it reaches the document object.

When you click on a child element, the event also gets triggered on its parent(s) unless you stop it.

<div id="parent" style="padding:20px; background:lightblue;">
Parent Div
<button id="child" style="margin:10px;">Click Me</button>
</div>

<script>
document.getElementById("child").addEventListener("click", function() {
alert("Child Button Clicked");
});

document.getElementById("parent").addEventListener("click", function() {
alert("Parent Div Clicked");
});

document.body.addEventListener("click", function() {
alert("Body Clicked");
});
</script>