0% found this document useful (0 votes)
4 views33 pages

JavaScript React Complete Notes

The document provides comprehensive study notes on JavaScript and React, covering six units that include basics, object-oriented programming, functions, the BOM and DOM, event handling, and an introduction to React components. Each unit is detailed with explanations, examples, and key concepts essential for understanding JavaScript and React. Topics range from data types and operators to advanced concepts like proxies, reflect methods, and component lifecycle in React.

Uploaded by

kavy3934
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)
4 views33 pages

JavaScript React Complete Notes

The document provides comprehensive study notes on JavaScript and React, covering six units that include basics, object-oriented programming, functions, the BOM and DOM, event handling, and an introduction to React components. Each unit is detailed with explanations, examples, and key concepts essential for understanding JavaScript and React. Topics range from data types and operators to advanced concepts like proxies, reflect methods, and component lifecycle in React.

Uploaded by

kavy3934
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

JavaScript & React

Complete Study Notes

Units I – VI | All Topics Explained with Examples

Basics · OOP · Functions · BOM/DOM · Events · React

Page 1
Table of Contents
Unit I – Basics of JavaScript
• Introduction, Executing JS, Syntax, Keywords
• Reserved Words, Data Types, Operators, Statements
• Primitive & Reference Values, Execution Context & Scope
• RegExp, Singleton Built-in Objects, Collection Reference Types
• Iterators & Generators
Unit II – OOP Concepts, Proxies & Reflect
• Understanding Objects, Object Creation, Inheritance
• Classes, Proxy Fundamentals, Proxy Traps & Reflect Methods
• Proxy Patterns
Unit III – Functions, Promises & Async
• Arrow Functions, Function Names, Arguments, Overloading
• Default Parameters, Spread, Function Expressions & Values
• Function Internals, Properties & Methods, Recursion, Closures
• Async Programming, Promises, Sync Functions
Unit IV – The BOM and DOM
• Window, Location, Navigator, Screen, History Objects
• Client Detection, Capacity Detection, User-Agent Detection
• DOM Hierarchy, Working with DOM, Mutation Observers
Unit V – Event Handling & JavaScript APIs
• Event Flow, Handlers, Object, Types, Memory
• Scripting Forms, Text Boxes, Select Boxes, Serialisation, Rich Text
• Atomics, Cross-Context Messaging, Encoding API, Blob & File
• Media Events, Drag & Drop, Notifications, Page Visibility
• Stream API, Timing APIs, Web Components, Web Crypto
Unit VI – Introduction to React & Components
• Intro to React, Components & Lifecycle, Styling
• Properties, State, UI, Events, Accessing DOM, External Data

Page 2
UNIT I Basics of JavaScript

1. Introduction to JavaScript
JavaScript is a lightweight, interpreted, high-level programming language primarily used to make web
pages interactive. It runs directly in the browser without needing compilation. JavaScript was created by
Brendan Eich in 1995 and is now one of the core technologies of the web alongside HTML and CSS.

JavaScript can manipulate HTML content, respond to user events, fetch data from servers, and much
more. It follows the ECMAScript standard (ES6, ES2020, etc.) for its syntax and features.

■ Example:
// A simple JavaScript greeting

[Link]("Hello, World!");

// JavaScript in HTML

<script>alert("Welcome to JavaScript!");</script>

2. Executing JavaScript
JavaScript can be executed in multiple ways:

a) In the Browser: Write JS inside <script> tags or link an external .js file. The browser's JavaScript
engine (like V8 in Chrome) executes it.

b) Using [Link]: [Link] lets you run JavaScript outside the browser, on the server or terminal.

c) Browser Console: Open DevTools (F12) → Console and type JS directly.

■ Example:
// Inline in HTML

&lt;script&gt;[Link]("Runs in browser");&lt;/script&gt;

// External file ([Link])

&lt;script src="[Link]"&gt;&lt;/script&gt;

// [Link] terminal

$ node [Link]

3. Syntax
Syntax refers to the rules for writing correct JavaScript code. Key rules include: statements end with a
semicolon (;), code blocks are enclosed in curly braces {}, and identifiers are case-sensitive.

■ Example:
var name = 'Alice'; // variable declaration

let age = 25; // block-scoped variable

const PI = 3.14; // constant

Page 3
if (age > 18) {

[Link]("Adult");

4. Keywords
Keywords are special words that have a predefined meaning in JavaScript. They cannot be used as
variable names. Examples include: var, let, const, if, else, for, while, function, return, class, import, export,
new, this, typeof, null, true, false, break, continue, switch, case, default, try, catch, finally, throw.

■ Example:
let score = 10; // 'let' is a keyword

if (score > 5) { // 'if' is a keyword

return true; // 'return' is a keyword

5. Reserved Words
Reserved words are words that are set aside for future use or are currently used by JavaScript. They
cannot be used as identifiers. Some reserved words include: abstract, boolean, byte, char, double, enum,
export, extends, final, float, goto, implements, import, int, interface, long, native, package, private,
protected, public, short, static, super, synchronized, throws, transient, volatile.

Using these as variable names will cause a SyntaxError.

■ Example:
// WRONG: 'class' is a reserved word

// var class = 5; → SyntaxError

// CORRECT:

var className = 5;

6. Data Types
JavaScript has two categories of data types: Primitive and Reference types.

Primitive Types:
Number: Represents both integers and floating-point numbers.

let x = 42; let pi = 3.14;

String: A sequence of characters enclosed in quotes.

let name = "Alice";

Boolean: Represents true or false.

let isLoggedIn = true;

Undefined: A variable declared but not assigned a value.

Page 4
let a; // a is undefined

Null: Explicitly represents no value.

let data = null;

Symbol: A unique, immutable identifier.

let sym = Symbol('id');

BigInt: For very large integers beyond Number limit.

let big = 9007199254740991n;

Reference Types:
Reference types include Objects, Arrays, and Functions. They store references (memory addresses)
rather than direct values.

let arr = [1, 2, 3]; // Array

let obj = { name: "Bob" }; // Object

let fn = function() {}; // Function

7. Operators
Operators are symbols that perform operations on values (operands).

Arithmetic Operator: Perform math: + - * / % **

let r = 10 % 3; // 1 (remainder)

Assignment Operator: Assign values: = += -= *= /=

let x = 5; x += 3; // x is now 8

Comparison Operator: Compare values: == === != !== > < >= <=

5 === '5' // false (strict)

Logical Operator: Combine booleans: && || !

true && false // false

Ternary Operator: Shorthand if-else: condition ? val1 : val2

let msg = age >= 18 ? "Adult" : "Minor";

typeof Operator: Returns the data type of a value

typeof 42 // "number"

Nullish ?? Operator: Returns right side if left is null/undefined

let val = null ?? "default"; // "default"

8. Statements
A statement is a complete instruction that JavaScript can execute. Types of statements:

Declaration Statements: Declare variables.

let count = 0;

Page 5
Expression Statements: Evaluate an expression.

count++;

Conditional Statements: Execute code based on conditions.

if (x > 0) { [Link]('Positive'); }

Loop Statements: Repeat code.

for (let i = 0; i < 5; i++) { [Link](i); }

Switch Statements: Multi-branch condition.

switch(day) { case 'Mon': [Link]('Monday'); break; }

Try/Catch Statements: Handle errors.

try { riskyCode(); } catch(e) { [Link](e); }

9. Primitive and Reference Values


Primitive Values are copied by value. When you assign a primitive to another variable, a fresh copy is
made. Changes to one do not affect the other.

let a = 10;

let b = a; // b gets a copy

b = 20;

[Link](a); // 10 → unchanged
Reference Values are copied by reference. Both variables point to the same object in memory, so
changes through one variable affect the other.

let obj1 = { name: "Alice" };

let obj2 = obj1; // both point to same object

[Link] = "Bob";

[Link]([Link]); // "Bob" → changed!

10. Execution Context and Scope


An Execution Context is the environment where JavaScript code is evaluated and executed. Every time a
function is called, a new execution context is created. The stack of contexts is called the Call Stack.

There are three types: Global Execution Context (created once), Function Execution Context (created
per function call), and Eval Context.

Scope defines the accessibility of variables. Types of scope:

Global Scope: Variables declared outside any function.

var globalVar = 'I am global';

Function Scope: Variables declared inside a function, accessible only within.

function greet() { let msg = 'Hi'; } // msg not accessible outside

Block Scope: Variables declared with let/const inside {}, accessible only in that block.

if(true) { let x = 5; } // x not accessible outside if

Page 6
Hoisting: JavaScript moves declarations to the top of their scope before execution. var is hoisted
(undefined), let/const are hoisted but not initialized (TDZ).

11. RegExp Type


A Regular Expression (RegExp) is a pattern used to match character combinations in strings. It is used
for searching, replacing, and validating text.

Syntax: /pattern/flags — Flags: g (global), i (case-insensitive), m (multiline).

■ Example:
let pattern = /hello/i; // matches 'Hello', 'HELLO', 'hello'

let str = "Hello World";

[Link]([Link](str)); // true

// Extract matches

let digits = "Phone: 9876543210";

let result = [Link](/\d+/);

[Link](result[0]); // "9876543210"

// Replace using regex

let clean = "foo bar".replace(/\s/g, "_");

[Link](clean); // "foo_bar"

12. Singleton Built-in Objects


JavaScript provides built-in objects that are always available without needing to create instances. Key
ones include:
Math: Provides mathematical functions and constants.

[Link](1,2,3) // 3

[Link](16) // 4

[Link] // 3.14159...

JSON: Converts between JavaScript objects and JSON strings.

[Link]({a:1}) // '{"a":1}'

[Link]('{"a":1}') // {a: 1}

Date: Creates and manipulates date/time.

let now = new Date();

[Link](); // current year

13. Collection Reference Types


These are built-in objects designed to hold collections of data.

Page 7
Array: An ordered list of values. Supports index-based access.

let fruits = ['apple', 'banana', 'cherry'];

[Link](fruits[1]); // 'banana'

[Link]('mango');

[Link]([Link]); // 4

Map: A collection of key-value pairs where keys can be any type.

let map = new Map();

[Link]('name', 'Alice');

[Link](1, 'one');

[Link]([Link]('name')); // 'Alice'

Set: A collection of unique values (no duplicates).

let set = new Set([1, 2, 2, 3]);

[Link]([Link]); // 3 (duplicates removed)

[Link](4);

[Link](2); // true

WeakMap: Like Map, but keys must be objects and are held weakly (garbage-collectible).

let wm = new WeakMap();

let key = {};

[Link](key, 'value');

[Link]([Link](key)); // 'value'

WeakSet: Like Set, but only holds objects and is weakly held.

let ws = new WeakSet();

let obj = {};

[Link](obj);

[Link](obj); // true

14. Iterators and Generators


An Iterator is an object that implements the iteration protocol: it has a next() method that returns {value,
done}. Arrays, Maps, and Sets are iterable by default.

let arr = [10, 20, 30];

let iter = arr[[Link]]();

[Link]([Link]()); // {value: 10, done: false}

[Link]([Link]()); // {value: 20, done: false}

[Link]([Link]()); // {value: 30, done: false}

[Link]([Link]()); // {value: undefined, done: true}


A Generator is a special function that can pause execution and resume later using the yield keyword.
Defined with function*.

Page 8
function* countUp() {

yield 1;

yield 2;

yield 3;

let gen = countUp();

[Link]([Link]().value); // 1

[Link]([Link]().value); // 2

[Link]([Link]().value); // 3

Page 9
UNIT II OOP Concepts, Proxies and Reflect

1. Understanding Objects
An object is a collection of key-value pairs called properties. Each property has a name (key) and a value.
Objects represent real-world entities. Properties can be data properties (hold values) or accessor
properties (get/set).

let person = {

name: 'Alice',

age: 25,

greet: function() { [Link]('Hello, I am ' + [Link]); }

};

[Link]([Link]); // 'Alice'

[Link](); // 'Hello, I am Alice'

2. Object Creation
There are several ways to create objects in JavaScript:

Object Literal
Simplest way, using curly braces.

let car = { make: 'Toyota', model: 'Corolla' };

Constructor Function
Function used with 'new' keyword to create multiple similar objects.

function Car(make, model) {

[Link] = make;

[Link] = model;

let c = new Car('Honda', 'Civic');

[Link]()
Creates an object with a specified prototype.

let proto = { greet() { [Link]('Hello'); } };

let obj = [Link](proto);

[Link](); // 'Hello'

Class Syntax
Modern ES6 way using class keyword (covered next).

class Dog { constructor(name) { [Link] = name; } }

let d = new Dog('Rex');

Page 10
3. Inheritance
Inheritance allows one object to acquire properties and methods of another. JavaScript uses prototypal
inheritance — every object has a prototype object it inherits from.

// Prototype chain example

function Animal(name) { [Link] = name; }

[Link] = function() {

[Link]([Link] + ' makes a sound.');

};

function Dog(name) { [Link](this, name); }

[Link] = [Link]([Link]);

[Link] = Dog;

[Link] = function() { [Link]('Woof!'); };

let dog = new Dog('Rex');

[Link](); // 'Rex makes a sound.'

[Link](); // 'Woof!'

4. Classes
ES6 introduced the class keyword as syntactic sugar over prototypal inheritance. Classes make OOP
cleaner and more readable.

class Animal {

constructor(name) { [Link] = name; }

speak() { [Link]([Link] + ' makes a sound.'); }

class Dog extends Animal {

bark() { [Link]([Link] + ' barks!'); }

let d = new Dog('Buddy');

[Link](); // 'Buddy makes a sound.'

[Link](); // 'Buddy barks!'

// Static methods

class MathHelper {

static add(a, b) { return a + b; }

Page 11
}

[Link](3, 4); // 7

5. Proxy Fundamentals
A Proxy is a wrapper around an object that intercepts and redefines fundamental operations on it (like
reading/writing properties). It is created with new Proxy(target, handler).

The target is the original object, and the handler contains trap methods that intercept operations.

let target = { name: 'Alice', age: 25 };

let proxy = new Proxy(target, {

get(obj, prop) {

return prop in obj ? obj[prop] : 'Not found';

});

[Link]([Link]); // 'Alice'

[Link]([Link]); // 'Not found'

6. Proxy Traps and Reflect Methods


Proxy traps are methods in the handler that intercept specific operations. Reflect is a built-in object with
methods mirroring the Proxy traps, useful for forwarding default behavior.

get(target, prop): Intercepts property reading.

set(target, prop, value): Intercepts property writing.


has(target, prop): Intercepts the 'in' operator.

deleteProperty(target, prop): Intercepts delete operator.

apply(target, thisArg, args): Intercepts function calls.

construct(target, args): Intercepts new operator.

let handler = {

set(obj, prop, value) {

if (typeof value !== 'number') throw new TypeError('Must be number');

return [Link](obj, prop, value);

};

let validated = new Proxy({}, handler);

[Link] = 95; // OK

// [Link] = "X"; // Throws TypeError

Page 12
7. Proxy Patterns
Common Proxy use patterns include:

Validation Proxy: Validates data before setting properties.

Logging Proxy: Logs every property access for debugging.

Read-only Proxy: Prevents writing to an object.

Default Value Proxy: Returns a default when property is missing.

// Read-only Proxy

let readOnly = new Proxy({ x: 10 }, {

set() { throw new Error('Object is read-only!'); }

});

[Link](readOnly.x); // 10

// readOnly.x = 20; // Error: Object is read-only!

Page 13
UNIT III Functions, Promises and Async Functions

1. Arrow Functions
Arrow functions are a concise way to write functions using the => syntax. They do not have their own this
binding — they inherit this from the enclosing context.

// Regular function

function add(a, b) { return a + b; }

// Arrow function

const add = (a, b) => a + b;

[Link](add(3, 4)); // 7

// Single parameter, no parentheses needed

const double = n => n * 2;

// No parameters

const greet = () => 'Hello!';

2. Function Names
Every function in JavaScript has a name property. Named functions help with debugging, as the name
appears in stack traces.

function sayHi() {}

[Link]([Link]); // 'sayHi'

const greet = function hello() {};

[Link]([Link]); // 'hello'

const fn = () => {};

[Link]([Link]); // 'fn'

3. Understanding Arguments
The arguments object is an array-like object available inside regular functions that contains all passed
arguments, even if not declared in the function signature.

function sum() {

let total = 0;

for (let i = 0; i < [Link]; i++) {

total += arguments[i];

Page 14
}

return total;

[Link](sum(1, 2, 3, 4)); // 10

// Note: Arrow functions do NOT have 'arguments'

4. No Overloading
JavaScript does not support function overloading (defining the same function with different parameters). If
you define two functions with the same name, the second overwrites the first. You can simulate
overloading using default parameters or checking argument types.

// This second definition overwrites the first

function greet(name) { return 'Hello ' + name; }

function greet() { return 'Hello stranger'; }

[Link](greet('Alice')); // 'Hello stranger' (overwritten!)

// Simulated overloading:

function greet(name = 'stranger') { return 'Hello ' + name; }

greet(); // 'Hello stranger'

greet('Alice'); // 'Hello Alice'

5. Default Parameter Values


Default parameter values allow you to specify fallback values for function parameters when no argument
(or undefined) is passed.

function greet(name = 'World') {

[Link]('Hello, ' + name + '!');

greet(); // 'Hello, World!'

greet('Alice'); // 'Hello, Alice!'

// Can use expressions as defaults

function multiply(a, b = a * 2) { return a * b; }

multiply(3); // 3 * 6 = 18

multiply(3, 4); // 3 * 4 = 12

6. Spread Arguments
The spread operator (...) expands an array into individual arguments when calling a function. It can also
collect remaining arguments into an array (rest parameters).

Page 15
// Spread: expand array into args

function add(a, b, c) { return a + b + c; }

let nums = [1, 2, 3];

[Link](add(...nums)); // 6

// Rest: collect args into array

function sum(...numbers) {

return [Link]((acc, n) => acc + n, 0);

[Link](sum(1, 2, 3, 4)); // 10

7. Function Expressions
A function expression defines a function as part of an expression (e.g., assigned to a variable). Unlike
function declarations, they are not hoisted.

// Function Declaration (hoisted)

[Link](greet()); // Works even before declaration

function greet() { return 'Hello'; }

// Function Expression (NOT hoisted)

// [Link](greet2()); // ERROR!

const greet2 = function() { return 'Hi'; };

[Link](greet2()); // Works after assignment

8. Functions as Values
In JavaScript, functions are first-class citizens — they can be assigned to variables, passed as arguments
to other functions, and returned from functions.

// Assigned to variable

const sayHi = function() { return 'Hi'; };

// Passed as argument (callback)

function doTwice(fn) { fn(); fn(); }

doTwice(() => [Link]('Hello!'));

// Returned from a function (higher-order)

function multiplier(x) {

return function(y) { return x * y; };

const triple = multiplier(3);

Page 16
[Link](triple(5)); // 15

9. Function Internals
this refers to the object that called the function. Its value depends on how the function is called.

const obj = {

name: 'Alice',

greet() { [Link]('Hi, I am ' + [Link]); }

};

[Link](); // 'Hi, I am Alice'

// call(), apply(), bind() control 'this'

function introduce(city) { [Link]([Link] + " from " + city); }

[Link]({ name: "Bob" }, "Delhi"); // Bob from Delhi

[Link]({ name: "Eve" }, ["Mumbai"]); // Eve from Mumbai

let fn = [Link]({ name: "Sam" });

fn("Chennai"); // Sam from Chennai

10. Function Properties and Methods


Functions in JavaScript are objects and have properties and methods:

name — the function's name. length — number of declared parameters. call() — calls with explicit this.
apply() — like call but takes array. bind() — returns a new function with fixed this.

function greet(a, b) {}

[Link]([Link]); // 2 (two parameters)

[Link]([Link]); // 'greet'

11. Recursion
Recursion is when a function calls itself. Every recursive function needs a base case (stop condition) to
avoid infinite loops.

// Factorial using recursion

function factorial(n) {

if (n === 0) return 1; // base case

return n * factorial(n - 1); // recursive call

[Link](factorial(5)); // 120 (5*4*3*2*1)

// Fibonacci

function fib(n) {

if (n <= 1) return n;

Page 17
return fib(n-1) + fib(n-2);

[Link](fib(6)); // 8

12. Closures
A closure is a function that remembers variables from its outer scope even after the outer function has
finished executing. Closures give functions access to the scope in which they were defined.

function makeCounter() {

let count = 0; // private variable

return function() {

count++;

return count;

};

let counter = makeCounter();

[Link](counter()); // 1

[Link](counter()); // 2

[Link](counter()); // 3

// 'count' is not accessible from outside

13. Asynchronous Programming


JavaScript is single-threaded but supports asynchronous operations using callbacks, Promises, and
async/await. Async programming allows tasks like fetching data to run without blocking the main thread.

// Callback pattern

setTimeout(() => {

[Link]('This runs after 2 seconds');

}, 2000);

[Link]('This runs immediately');

14. Promises
A Promise is an object representing the eventual result of an asynchronous operation. It can be in one of
three states: Pending, Fulfilled, or Rejected.

let p = new Promise((resolve, reject) => {

let success = true;

if (success) resolve('Data loaded!');

else reject('Error occurred!');

});

Page 18
[Link](result => [Link](result))

.catch(error => [Link](error));

// Promise chaining

fetch('[Link]

.then(res => [Link]())

.then(data => [Link](data))

.catch(err => [Link](err));

15. Async/Await Functions


The async/await syntax is built on Promises and makes asynchronous code look like synchronous code.
An async function always returns a Promise. The await keyword pauses execution until the Promise
resolves.

async function fetchUser() {

try {

let response = await fetch('[Link]

let data = await [Link]();

[Link](data);

} catch (error) {

[Link]('Error:', error);

fetchUser();

Page 19
UNIT IV The BOM and DOM

1. The Browser Object Model (BOM)


The Browser Object Model (BOM) allows JavaScript to interact with the browser. The top-level object is
window, which represents the browser window/tab.

Window Object
The global object in browsers. All global variables and functions are properties of window.

[Link]([Link]); // viewport width

[Link]('Hello!');

[Link]; // current URL

Location Object
Contains information about the current URL and allows navigation.

[Link]([Link]); // full URL

[Link]([Link]); // domain

[Link] = '[Link] // navigate

[Link](); // reload page

Navigator Object
Provides info about the browser and OS.

[Link]([Link]); // browser info

[Link]([Link]); // "en-US"

[Link]([Link]); // true/false

Screen Object
Contains info about the user's screen.

[Link]([Link]); // screen width in px

[Link]([Link]); // screen height in px

[Link]([Link]); // color depth

History Object
Allows navigation through browser session history.

[Link](); // go to previous page

[Link](); // go to next page

[Link](-2); // go 2 pages back

2. Client Detection

Page 20
Client detection helps determine the user's browser, device, or capabilities to provide the best experience.

Capability Detection
Check if a feature exists before using it — the preferred approach.

if (typeof fetch !== 'undefined') {

fetch('/api/data'); // use fetch if supported

} else {

// fallback for older browsers

User-Agent Detection
Read the [Link] string to identify the browser. Less reliable due to spoofing.

let ua = [Link];

if ([Link]("Chrome")) { [Link]("Chrome browser"); }

if ([Link]("Firefox")) { [Link]("Firefox browser"); }

Software & Hardware Detection


Detect device memory, CPU cores, and connection type.

[Link]([Link]); // CPU cores

[Link]([Link]); // GB of RAM

[Link]([Link]); // '4g'

3. The Document Object Model (DOM)


The Document Object Model (DOM) is a programming interface for HTML/XML documents. It represents
the page as a tree of nodes that JavaScript can read and modify.

Hierarchy of Nodes
The DOM is organized as a tree. The top node is document. Below it are element nodes (<html>, <body>,
etc.), text nodes, comment nodes, and attribute nodes.

document → root

■■ html

■■ head

■ ■■ title (text: 'My Page')

■■ body

■■ h1 (text: 'Hello')

■■ p (text: 'World')

Working with the DOM


JavaScript can select, modify, create, and delete DOM elements:

// Selecting elements

Page 21
let h1 = [Link]('title');

let paras = [Link]('p');

// Modifying content

[Link] = 'New Title';

[Link] = "red";

// Creating & appending

let newEl = [Link]('div');

[Link] = 'I am new!';

[Link](newEl);

// Removing

let old = [Link]('old');

[Link](old);

Mutation Observers
A MutationObserver watches for changes in the DOM (like added/removed nodes or attribute changes)
and calls a callback when changes happen.

let observer = new MutationObserver(mutations => {

[Link](m => [Link]('Change:', [Link]));

});

[Link]([Link], {

childList: true, // watch for child additions/removals

attributes: true, // watch attribute changes

subtree: true // observe all descendants too

});

// To stop observing:

[Link]();

Page 22
UNIT V Event Handling and JavaScript APIs

1. Events

Event Flow
When an event occurs, it travels in three phases: Capturing Phase (top to target), Target Phase (at the
element), and Bubbling Phase (bottom to top). By default, events are handled in the bubbling phase.

// stopPropagation prevents bubbling

[Link]('click', function(e) {

[Link]();

[Link]('Button clicked, no bubbling');

});

Event Handlers
Event handlers are functions that execute when an event fires. They can be assigned via HTML attributes,
DOM properties, or addEventListener.

// addEventListener (preferred)

[Link]("btn").addEventListener("click", function() {

[Link]("Button was clicked!");

});

// Remove listener

function handler() { [Link]('clicked'); }

[Link]("click", handler);

[Link]("click", handler);

Event Object
The event object is automatically passed to the handler and contains useful information about the event.

[Link]("click", function(event) {

[Link]([Link]); // 'click'

[Link]([Link]); // element that was clicked

[Link]([Link]); // mouse X position

[Link](); // prevent default action

});

Types of Events
Mouse Events: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove

Keyboard Events: keydown, keyup, keypress

Page 23
Form Events: submit, change, input, focus, blur, reset

Window Events: load, resize, scroll, unload, DOMContentLoaded

Touch Events: touchstart, touchend, touchmove

Drag Events: dragstart, drag, dragend, drop

Memory and Performance


Adding too many event listeners can slow down the page. Use event delegation — attach one listener to
a parent element and check the target.

// Instead of adding listeners to each li:

[Link]("list").addEventListener("click", function(e) {

if ([Link] === "LI") {

[Link]('Clicked:', [Link]);

});

2. Scripting Forms

Form Basics
HTML forms collect user input. JavaScript can access form data, validate inputs, and handle submission.

let form = [Link]("myForm");

[Link]("submit", function(e) {

[Link](); // stop page reload

let name = [Link]("name").value;

[Link]("Submitted:", name);

});

Scripting Text Boxes


Text inputs can be read, changed, and validated programmatically.

let input = [Link]("username");

[Link] = 'default'; // set value

[Link](); // select all text

[Link](); // focus the input

// Validate on input

[Link]("input", () => {

if ([Link] < 3) [Link] = "1px solid red";

});

Scripting Select Boxes

Page 24
Select (dropdown) elements can have options dynamically added and the selected value read.

let sel = [Link]("country");

[Link]([Link]); // selected value

[Link]([Link]);

// Add option dynamically

let opt = new Option("India", "IN");

[Link](opt);

Form Serialisation
Serialization converts form data into a string or object for submission. FormData API makes this easy.

let form = [Link]("myForm");

let data = new FormData(form);

for (let [key, val] of [Link]()) {

[Link](key, val);

// Or send directly:

fetch('/submit', { method: 'POST', body: data });

3. Key JavaScript APIs

Atomics and SharedArrayBuffer


SharedArrayBuffer lets multiple workers share memory. Atomics provides atomic operations to prevent
race conditions.

let sab = new SharedArrayBuffer(16);

let arr = new Int32Array(sab);

[Link](arr, 0, 5);

[Link]([Link](arr, 0)); // 5

Cross-Context Messaging (postMessage)


postMessage allows safe communication between different windows, iframes, or workers.

[Link]("Hello!", "[Link]

[Link]('message', function(e) {

[Link]('Received:', [Link]);

});

Encoding API
TextEncoder and TextDecoder convert between strings and binary data (Uint8Array).

let enc = new TextEncoder();

Page 25
let bytes = [Link]("Hello");

[Link](bytes); // Uint8Array

let dec = new TextDecoder();

[Link]([Link](bytes)); // 'Hello'

Blob and File APIs


Blob represents raw binary data. File extends Blob and includes file metadata.

let blob = new Blob(["Hello World"], { type: "text/plain" });

let url = [Link](blob);

// Use url in an anchor tag to download

// File from input

let fileInput = [Link]("file");

let file = [Link][0];

[Link]([Link], [Link]);

Notifications API
Shows desktop notifications to the user (requires permission).

[Link]().then(p => {

if (p === "granted") {

new Notification("Hello!", { body: "You have a new message" });

});

Page Visibility API


Detects when the user switches tabs or minimizes the browser.

[Link]("visibilitychange", () => {

if ([Link]) [Link]("Tab is hidden");

else [Link]("Tab is visible");

});

Timing APIs (Performance)


[Link]() gives high-resolution timestamps for measuring code performance.

let start = [Link]();

// ... code to measure ...

let end = [Link]();

[Link]('Time:', end - start, 'ms');

Web Components
Web Components let you create custom, reusable HTML elements.

Page 26
class MyGreeting extends HTMLElement {

connectedCallback() {

[Link] = '<h2>Hello from Web Component!</h2>';

[Link]('my-greeting', MyGreeting);

// Use in HTML: <my-greeting></my-greeting>

Web Cryptography API


Provides cryptographic operations like hashing, encryption, and key generation.

async function hashData(data) {

let encoded = new TextEncoder().encode(data);

let hashBuffer = await [Link]('SHA-256', encoded);

return hashBuffer;

hashData('Hello').then(h => [Link](h));

Page 27
UNIT VI Introduction to Framework – React

1. Introduction to React
React is a JavaScript library developed by Facebook (Meta) for building fast, interactive user interfaces. It
uses a component-based architecture where the UI is broken into small, reusable pieces called
components.

React uses a Virtual DOM — a lightweight copy of the real DOM — to efficiently update only the parts of
the page that actually changed, making it very fast.

// Install React (using Create React App)

npx create-react-app my-app

cd my-app

npm start

// Basic React element (JSX)

const element = <h1>Hello, React!</h1>;

[Link](element, [Link]('root'));

2. Components and Their Lifecycle


A component is a self-contained piece of UI that returns JSX (HTML-like syntax). Components can be
Function Components (simple) or Class Components (older, with more features).

Function Component
function Welcome(props) {

return <h1>Hello, {[Link]}!</h1>;

// Usage:

<Welcome name='Alice' />

Class Component (with Lifecycle)


Class components have lifecycle methods called at different stages of a component's life:

class MyComponent extends [Link] {

constructor(props) {

super(props);

[Link] = { count: 0 };

componentDidMount() {

// Runs after component is added to DOM

Page 28
[Link]('Component mounted!');

componentDidUpdate(prevProps, prevState) {

// Runs after state/props change

[Link]('Component updated!');

componentWillUnmount() {

// Runs before component is removed

[Link]('Component will unmount');

render() {

return <div>Count: {[Link]}</div>;

3. Styling in React
React supports multiple ways to style components:

Inline Styles
Pass a style object directly to JSX elements. Use camelCase for property names.

const style = { color: "blue", fontSize: "20px" };

<h1 style={style}>Hello</h1>

CSS Classes
Import an external CSS file and use className (not class).

import "./[Link]";

<div className="card">Content</div>

CSS Modules
Scoped CSS — class names are unique per component.

import styles from "./[Link]";

<div className={[Link]}>Content</div>

4. Properties (Props)
Props (properties) are read-only data passed from a parent component to a child component. They allow
components to be dynamic and reusable.

Page 29
// Parent passes props

function App() {

return <UserCard name='Alice' age={25} />;

// Child receives props

function UserCard(props) {

return (

<div>

<h2>{[Link]}</h2>

<p>Age: {[Link]}</p>

</div>

);

5. State
State is data that belongs to a component and can change over time. When state changes, React
re-renders the component. In function components, state is managed using the useState hook.

import { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0); // initial value = 0

return (

<div>

<p>Count: {count}</p>

<button onClick={() => setCount(count + 1)}>+</button>

<button onClick={() => setCount(count - 1)}>-</button>

</div>

);

6. UI (Rendering & JSX)


JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code inside JavaScript. JSX is
compiled to [Link]() calls.

// JSX

const element = (

<div className='card'>

Page 30
<h1>Hello!</h1>

<p>Welcome to React.</p>

</div>

);

// Conditional rendering

function Greeting({ isLoggedIn }) {

return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>;

// Lists with .map()

const fruits = ['Apple', 'Banana', 'Mango'];

const list = [Link](f => <li key={f}>{f}</li>);

7. Events in React
React events are similar to DOM events but use camelCase names (onClick, onChange, onSubmit) and
pass a synthetic event object.

function Button() {

function handleClick(e) {

[Link]();

[Link]('Button clicked!', [Link]);

return <button onClick={handleClick}>Click Me</button>;

// Input onChange

function NameInput() {

const [name, setName] = useState('');

return (

<input

value={name}

onChange={e => setName([Link])}

placeholder='Enter name'

/>

);

8. Accessing DOM Elements (useRef)

Page 31
The useRef hook provides a way to directly access a DOM element in React without causing re-renders.
It's commonly used for focusing inputs, reading values, or integrating with third-party libraries.

import { useRef } from 'react';

function FocusInput() {

const inputRef = useRef(null);

function focusIt() {

[Link](); // directly access DOM node

return (

<div>

<input ref={inputRef} placeholder='I will be focused' />

<button onClick={focusIt}>Focus Input</button>

</div>

);

9. Handling External Data (useEffect + Fetch)


The useEffect hook lets you perform side effects in function components — such as fetching data from an
API when a component mounts.

import { useState, useEffect } from 'react';

function UserList() {

const [users, setUsers] = useState([]);

const [loading, setLoading] = useState(true);

useEffect(() => {

fetch('[Link]

.then(res => [Link]())

.then(data => {

setUsers(data);

setLoading(false);

});

}, []); // empty array = run once on mount

if (loading) return <p>Loading...</p>;

Page 32
return (

<ul>

{[Link](u => <li key={[Link]}>{[Link]}</li>)}

</ul>

);

— End of JavaScript & React Complete Notes —

Page 33

You might also like