0% found this document useful (0 votes)
12 views68 pages

JAVASCRIPT

end to end javascript

Uploaded by

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

JAVASCRIPT

end to end javascript

Uploaded by

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

Web cookies are small text files that websites save on a user's device (like a computer or

smartphone) to remember information about a user's browsing activity or to help the website
function properly. These cookies are created by the websites a user visits and can be temporary
(session cookies) or permanent (persistent cookies).
Here’s a clear and structured explanation for each of your points:

How Cookies Work:

Cookies are small text files stored on a user’s browser by a website. When you visit a website:

1. The website sends a cookie to your browser.

2. The browser saves the cookie locally on your device.

3. When you visit the website again, your browser sends the cookie back to the server.

4. The server reads the cookie to remember your previous activity, preferences, or login state.

This helps the website maintain a consistent user experience.

Why Cookies are Used:

Cookies are used for several important reasons, including:

1. Session Management

o Remember login status

o Store user sessions across pages

2. Personalization

o Save language settings

o Remember user preferences (e.g., theme, layout)

3. Tracking and Analytics

o Track user behaviour (pages visited, time spent)

o Help site owners improve user experience

4. Targeted Advertising

o Serve relevant ads based on user activity and interests

Types of Cookies:

1. Session Cookies

o Temporary cookies that are deleted when the browser is closed

o Used for session management (e.g., keeping users logged in)


2. Persistent Cookies

o Remain on the device until they expire or are manually deleted

o Used for remembering login info, language, and other settings

3. First-Party Cookies

o Set by the website you are visiting

o Used for remembering user preferences and settings

4. Third-Party Cookies

o Set by domains other than the one you're visiting

o Commonly used for tracking and advertising across websites

5. Secure Cookies

o Only transmitted over HTTPS connections

o Help ensure cookie data is encrypted during transmission

6. HttpOnly Cookies

o Inaccessible via JavaScript

o Help prevent cross-site scripting (XSS) attacks

Let me know if you'd like visual diagrams, examples, or use cases for these!

Introduction to JavaScript (JS)

 JavaScript is a versatile, interpreted programming language primarily used to create dynamic


and interactive content on web pages. It runs in the browser but can also run on servers
(e.g., Node.js).
JavaScript is a single-threaded language that executes one task at a time.

 It is an Interpreted language which means it executes the code line by line.

 The data type of the variable is decided at run-time in JavaScript that’s why it is
called dynamically typed.

Multi-line Comment: The /* */ syntax

Single-line Comment: The // syntax

Key Features of JavaScript

Key Features of JavaScript:

1. Lightweight – Runs in the browser, uses minimal resources.


2. Interpreted – Code runs directly, without compiling.

3. Object-Based – Supports built-in objects and custom objects.

4. Event-Driven – Handles events like clicks and keystrokes.

5. Functional Style – Functions are first-class citizens.

6. Platform Independent – Works on all operating systems with browsers.

7. Dynamic Typing – Variable types are determined at runtime.

8. Asynchronous Processing – Supports async behavior using callbacks, promises, and


async/await.

✅ Client-Side and Server-Side Nature of JavaScript:

 Client-Side JavaScript:
Runs in the browser (e.g., DOM manipulation, form validation, animations).
Example:

js

CopyEdit

document.getElementById("btn").addEventListener("click", () => alert("Clicked!"));

 Server-Side JavaScript:
Runs on the server using environments like Node.js. Handles backend logic (e.g., databases,
file systems).
Example with Node.js:

js

CopyEdit

const http = require("http");

http.createServer((req, res) => {

res.end("Hello from server!");

}).listen(3000);

✅ Programming Paradigms in JavaScript:

1. Procedural – Use of functions and statements.

2. Object-Oriented – Uses classes and objects.

3. Functional – Uses pure functions, higher-order functions, and immutability.

✅ JavaScript is multi-paradigm: You can use a mix of all three.


✅ Applications of JavaScript:

1. Web Development – Frontend interactivity, dynamic UI.

2. Backend Development – Using Node.js.

3. Mobile App Development – Frameworks like React Native.

4. Game Development – Using Canvas or WebGL.

5. Desktop Apps – With Electron.js.

6. IoT and Smart Devices – With Node.js.

✅ Limitations of JavaScript:

1. Client-side security – Code is visible to users.

2. Browser incompatibility – Some features may not work in all browsers.

3. Single-threaded – Can lead to performance issues.

4. No direct file access (in browsers) – Limited by sandboxing.

✅ Why is JavaScript known as a Lightweight Programming Language?

 Minimal setup – No need to install or configure a compiler.

 Runs directly in browsers – No heavy runtime needed.

 Flexible syntax – Easy to write and execute small snippets.

 Memory efficient – Suitable for interactive web pages.

✅ Is JavaScript Compiled or Interpreted or Both?

 Originally Interpreted: Runs line by line in the browser.

 Modern JS is Both:

o Modern JS engines (like V8) compile JS to machine code before executing (Just-in-
Time Compilation).

o So, JavaScript is interpreted and compiled.

✅ JavaScript Versions (Simple Overview):

Version Name/Feature

ES5 Classic JavaScript (used till ~2015)

ES6 Major update (let, const, arrow functions)


Version Name/Feature

ES7 Includes includes(), exponentiation **

ES8 async/await

ES9–13 Various new features, like optional chaining, nullish coalescing, top-level await, etc.

Using JavaScript in HTML

You can add JavaScript to an HTML page in three main ways:

1. Inline script:

<script>

alert('Hello, world!');

</script>

2. Internal script:

Inside the <head> or <body> tag:

<script>

console.log('This is internal JS');

</script>

3. External script:

Create a separate .js file (e.g., script.js):

<script src="script.js"></script>

Variables and Data Types

Declaring Variables

1. var Keyword

The var keyword is used to declare a variable. It has a function-scoped or globally-scoped


behaviour.

var n = 5;

console.log(n);

var n = 20; // reassigning is allowed

console.log(n);
Output

20

2. let Keyword

The let keyword is introduced in ES6, has block scope and cannot be re-declared in the same scope.

let n= 10;

n = 20; // Value can be updated

// let n = 15; //can not redeclare

console.log(n)

Output

20

3. const Keyword

The const keyword declares variables that cannot be reassigned. It's block-scoped as well.

const n = 100;

// n = 200; This will throw an error

console.log(n)

Output

100

 var (function scoped, older style)

 let (block scoped, preferred)

 const (block scoped, constant)

let name = "Alice"; // String

const age = 25; // Number

var isActive = true; // Boolean

Data Types

Primitive Datatypes

Primitive datatypes represent single values and are immutable.

1. Number: Represents numeric values (integers and decimals).


let n = 42;
let pi = 3.14;

2. String: Represents text enclosed in single or double quotes.

let s = "Hello, World!";

3. Boolean: Represents a logical value (true or false).

let bool= true;

4. Undefined: A variable that has been declared but not assigned a value.

let notAssigned;

console.log(notAssigned);
Output

undefined

5. Null: Represents an intentional absence of any value.

let empty = null;

6. Symbol: Represents unique and immutable values, often used as object keys.

let sym = Symbol('unique');

7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.

let bigNumber = 123456789012345678901234567890n;

Non-Primitive Datatypes

Non-primitive types are objects and can store collections of data or more complex entities.

1. Object: Represents key-value pairs.

let obj = {
name: "Amit",
age: 25
};

2. Array: Represents an ordered list of values.

let a = ["red", "green", "blue"];

3. Function: Represents reusable blocks of code.

function fun() {
console.log("GeeksforGeeks");
}

greet();

Operators
 Arithmetic: +, -, *, /, %

 Assignment: =, +=, -=

 Comparison: ==, ===, !=, !==, >, <, >=, <=

 Logical: &&, ||, !

 Ternary: condition ? exprIfTrue : exprIfFalse

 typeof is a JavaScript operator used to check the data type of a value or


variable.

Type Conversion and Coercion

 Type Conversion: Explicitly changing type using functions like Number(), String(), Boolean().

 Type Coercion: JavaScript automatically converts types in expressions.

Example:

'5' + 2 // '52' (number coerced to string)

'5' - 2 // 3 (string coerced to number)

Template literals (also called template strings) are string literals that allow embedded expressions,
multi-line strings, and string interpolation using backticks `, instead of quotes ' ' or " ".

🔧 Syntax:

javascript

Copy code

`string text ${expression} string text`

Control Flow Statements

 if, else if, else

 switch statement

 Loops: for, while, do...while

 break and continue

Example:

if (age > 18) {

console.log("Adult");
} else {

console.log("Minor");

Scope

 Global Scope: Variables declared outside functions or blocks.

 Function Scope: Variables declared with var inside functions.

 Block Scope: Variables declared with let or const inside {} blocks.

Example:

function example() {

var x = 10; // function scoped

if (true) {

let y = 20; // block scoped

console.log(x); // 10

console.log(y); // Error: y is not defined

Browser Console

 The browser console is a developer tool for running JS commands and debugging.

 Open it via F12 or Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac).

 Use console.log(), console.error(), console.warn() for output.

Example:

console.log("Hello from console!");

Functions

 Functions are reusable blocks of code that perform a task.

 Defined with the function keyword or as arrow functions (=>).

Example:

function greet(name) {

return `Hello, ${name}!`;


}

const greetArrow = (name) => `Hello, ${name}!`;


Function Expression:

A function stored in a variable.

const greet = function(name) {

return "Hello " + name;

};

console.log(greet("Asiya")); // Output: Hello Asiya

Difference from function declaration:


Function expressions are not hoisted, unlike function declarations.

Here is a clear and simple explanation of all your requested JavaScript function concepts:

✅ Arrow Functions

A shorter syntax for writing functions (introduced in ES6).

Syntax:

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

console.log(add(3, 4)); // Output: 7

Key Points:

 No need for the function keyword.

 If only one parameter → parentheses optional.

 No this binding (uses lexical this).

✅ Immediately Invoked Function Expression (IIFE)

A function that runs immediately after it's defined.

Syntax:

(function() {

console.log("IIFE is running!");

})();

Or with arrow function:

(() => {
console.log("Arrow IIFE running!");

})();

Use Case:
Avoids polluting global scope and runs setup code immediately.

✅ Callback Functions

A function passed as an argument to another function, to be called later.

Example:

function greet(name, callback) {

console.log("Hello " + name);

callback();

function sayBye() {

console.log("Goodbye!");

greet("Asiya", sayBye);

Use Case:
Used in asynchronous operations like setTimeout, event handling, fetch.

✅ Anonymous Functions

A function without a name, often used as a value or argument.

Example:

setTimeout(function() {

console.log("This is an anonymous function.");

}, 1000);

Also used in:

const sum = function(a, b) {

return a + b;

};
✅ Nested Functions

A function defined inside another function.

Example:

function outer() {

let outerVar = "I am outer";

function inner() {

console.log(outerVar); // Can access outer function’s variable

inner();

outer();

Use Case:
Encapsulation, closures, and modular design.

✅ Pure Functions

A function that:

1. Always returns the same output for the same input.

2. Doesn’t modify any external state or variable.

Example:

function multiply(a, b) {

return a * b;

Impure Example:

let count = 0;

function increase() {

count++;

return count;

}
✅ Key Characteristics of Functions in JavaScript:

Characteristic Description

First-class citizens Functions can be stored in variables, passed as arguments, or returned.

Hoisting Function declarations are hoisted to the top of their scope.

Closures Functions can remember and access variables from their outer scope.

Lexical Scope Functions access variables from the scope in which they were defined.

Reusability Code can be reused by calling the function multiple times.

Anonymous/Pure/Nested Various types support different use cases.

Arrow Functions Provides concise syntax and lexical this.

Function Binding

In JavaScript, function binding means setting the value of “this” explicitly when a function is called.

🔸 Why Use Binding?

Because this depends on how a function is called, not where it's defined. To control it, we use
binding.

✅ Methods of Function Binding

1. bind() :The bind() method creates a new function with “this” set to the given
object.
let boundFunc = originalFunc.bind(object);

2. call() – Immediately calls the function with a given this and arguments.

func.call(object, arg1, arg2, ...);

3. apply() – Same as call() but takes arguments as an array.

func.apply(object, [arg1, arg2, ...]);

js

Copy code

function sayHello(city) {

console.log(`${this.name} from ${city}`);

}
const user = { name: "Asiya" };

sayHello.call(user, "Hyderabad"); // Asiya from Hyderabad

sayHello.apply(user, ["Delhi"]); // Asiya from Delhi

const bound = sayHello.bind(user);

bound("Mumbai");

Hoisting

 JS moves declarations (variables and functions) to the top of their scope before execution.

 Function declarations are hoisted fully; variables declared with var are hoisted but not
initialized.

 let and const are hoisted but remain in "temporal dead zone" until initialized.

Example:

console.log(foo); // undefined (var hoisted)

var foo = 5;

bar(); // Works due to function hoisting

function bar() {

console.log("Hello");

✅ Variable Hoisting with var, let, and const

Hoisting means moving declarations to the top of the scope.

 var is hoisted and initialized as undefined

 let and const are hoisted but not initialized → Temporal Dead Zone

js

Copy code

console.log(a); // undefined

var a = 10;

console.log(b); // ReferenceError
let b = 20;

✅ Function Declaration Hoisting

Function declarations are fully hoisted.

js

Copy code

greet(); // Works

function greet() {

console.log("Hello");

✅ Function Expression Hoisting

Only the variable name is hoisted, not the function.

js

Copy code

greet(); // TypeError: greet is not a function

var greet = function() {

console.log("Hello");

};

✅ Hoisting with Classes

Class declarations are hoisted but not initialized → like let.

js

Copy code

const obj = new MyClass(); // ReferenceError

class MyClass {

constructor() {

this.name = "Asiya";

}
✅ Using Hoisted Functions with Parameters

You can pass parameters to hoisted functions as usual:

js

Copy code

console.log(add(2, 3)); // 5

function add(a, b) {

return a + b;

Closures

A closure is created when an inner function remembers and has access to the variables of its outer
function, even after the outer function has finished executing.

function outer() {

let name = "Asiya";

function inner() {

console.log("Hello, " + name);

return inner;

let greet = outer(); // outer() runs, inner is returned

greet(); // Output: Hello, Asiya

Where Closures are Useful:

1. Data hiding / private variables

2. Creating function factories

3. Callback functions

4. Maintaining state in async code

✅ Lexical Scoping

In JavaScript, lexical scope means that an inner function can access the variables of its outer
function, but the outer function cannot access the variables of the inner function.
function outer() {

let name = "Asiya"; // outer variable

function inner() {

console.log(name); // inner function accessing outer variable

inner();

outer(); // Output: Asiya

✅ Private Variables

Using closures, we can create private variables:

js

Copy code

function counter() {

let count = 0;

return {

increment: () => ++count,

getCount: () => count

};

const c = counter();

console.log(c.increment()); // 1

console.log(c.getCount()); // 1

✅ Closures and IIFE

Closures + IIFE = Powerful combo for data hiding:

js

Copy code

const add = (function() {


let counter = 0;

return function() {

counter += 1;

return counter;

};

})();

console.log(add()); // 1

console.log(add()); // 2

✅ Closure and setTimeout

Closures help fix the common loop + setTimeout problem:

❌ Wrong:

js

Copy code

for (var i = 1; i <= 3; i++) {

setTimeout(() => console.log(i), 1000); // Prints 4, 4, 4

✅ Right:

js

Copy code

for (let i = 1; i <= 3; i++) {

setTimeout(() => console.log(i), 1000); // Prints 1, 2, 3

Or use closure:

js

Copy code

for (var i = 1; i <= 3; i++) {

(function(i) {

setTimeout(() => console.log(i), 1000);

})(i);
}

✅ Closures with this Keyword

Closures don't bind this, so be careful:

js

Copy code

function outer() {

this.name = "Asiya";

return function() {

console.log(this.name); // 'this' depends on caller

};

const func = outer();

func(); // undefined (in strict mode)

Fix it with arrow function:

js

Copy code

function outer() {

this.name = "Asiya";

return () => {

console.log(this.name); // 'this' refers to outer

};

const f = outer.call({ name: "Shaik" });

f(); // Shaik

✅ Benefits of Closures

1. Data hiding / encapsulation

2. Private variables
3. Factory functions

4. Function factories

5. State management in functional programming

Higher-Order Functions

 Functions that take other functions as arguments or return functions.

Example:

function greet(name, formatter) {

return "Hello, " + formatter(name);

function upperCaseName(name) {

return name.toUpperCase();

console.log(greet("Alice", upperCaseName)); // Hello, ALICE

✅ Popular Higher-Order Functions in JavaScript

These functions take another function as an argument or return one.

Function Purpose

map() Transform each element in an array

filter() Return elements that match a condition

reduce() Accumulate values into a single result

forEach() Loop through each element (no return value)

some() Check if at least one element passes test

every() Check if all elements pass a test

find() Returns the first matching element

sort() Sorts the elements

Example:

js

Copy code
const arr = [1, 2, 3, 4];

const doubled = arr.map(x => x * 2); // [2, 4, 6, 8]

Here’s a simple explanation of map(), filter(), reduce(), and forEach() in JavaScript with definition
and syntax:

✅ 1. map()

🔹 Definition:

The map() method creates a new array by applying a function to each element of the original array.

🔹 Syntax:

array.map(function(element, index, array) {

// return new value

});

🔹 Example:

let nums = [1, 2, 3];

let doubled = nums.map(num => num * 2);

console.log(doubled); // [2, 4, 6]

✅ 2. filter()

🔹 Definition:

The filter() method creates a new array with elements that pass a condition provided by a function.

🔹 Syntax:

array.filter(function(element, index, array) {

// return true to keep the element

});

🔹 Example:

let nums = [1, 2, 3, 4];

let evens = nums.filter(num => num % 2 === 0);

console.log(evens); // [2, 4]

✅ 3. reduce()

🔹 Definition:
The reduce() method reduces the array to a single value by executing a function for each element
(like adding, multiplying, etc.).

🔹 Syntax:

array.reduce(function(accumulator, currentValue, index, array) {

// return updated accumulator

}, initialValue);

🔹 Example:

let nums = [1, 2, 3, 4];

let sum = nums.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // 10

✅ 4. forEach()

🔹 Definition:

The forEach() method executes a function for each element in the array, but does not return a new
array.

🔹 Syntax:

array.forEach(function(element, index, array) {

// perform action

});

🔹 Example:

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

fruits.forEach(fruit => console.log(fruit));

// Output:

// apple

// banana

// cherry

✅ Summary Table:

Method Returns New Array? Used For

map() ✅ Yes Transforming elements

filter() ✅ Yes Filtering elements based on a condition


Method Returns New Array? Used For

reduce() ❌ No (returns value) Reducing array to a single value

forEach() ❌ No Looping through array

Let me know if you want practice problems or a PDF summary!

Iterator

An iterator is an object that allows you to go through a collection (like an array) one item at a time.

✅ How Does It Work?

An iterator has a next() method, which returns:

value: <current value>,

done: <true/false>

 value: the current item

 done: true if the end is reached, false otherwise

let numbers = [10, 20, 30];

// Create an iterator

let iterator = numbers[Symbol.iterator]();

console.log(iterator.next()); // { value: 10, done: false }

console.log(iterator.next()); // { value: 20, done: false }

console.log(iterator.next()); // { value: 30, done: false }

console.log(iterator.next()); // { value: undefined, done: true }

Iterators are used behind the scenes in:

 for...of loops

 ...spread operator

 Generators

 Custom iteration logic


for…of loop
Used to iterate over iterable objects like arrays, strings, maps, sets, etc.

Syntax:

for (let item of iterable) {

// code to run

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

for (let fruit of fruits) {

console.log(fruit);

Output:

apple

banana

cherry

Works on arrays, strings, maps, sets – but not on objects directly.

Function Generator

 Functions that can pause and resume execution, defined with function* and use yield.

Example:

function* generator() {

yield 1;

yield 2;

yield 3;

const gen = generator();

console.log(gen.next()); // { value: 1, done: false }

console.log(gen.next()); // { value: 2, done: false }

console.log(gen.next()); // { value: 3, done: false }

console.log(gen.next()); // { value: undefined, done: true }


Events

 Actions or occurrences in the system that the code can respond to.

 Examples: click, mouseover, keydown.

 ✅ Event Types

 Event Type  Description

 Mouse  click, dblclick, mouseover

 Keyboard  keydown, keyup, keypress

 Form  submit, change, focus, blur

 Window  load, resize, scroll, unload

 Touch  touchstart, touchend


 ✅ What is Event Handling?

 Event handling means writing code to respond to user actions or browser events.

 ✅ Event Handling Methods

1. Inline Event Handling


🔹 Syntax (in HTML):
<button onclick="sayHello()">Click Me</button>
🔹 JavaScript:
function sayHello() {
alert("Hello!");
}
2. Using HTML DOM Property

element.onclick = function() {

// your code

};

Eg:

<button id="btn">Click</button>

<script>

document.getElementById("btn").onclick = function() {

alert("Button clicked!");

};
</script>

3. Using addEventListener() (Best Practice ✅):addEventListener is a JavaScript method used


to attach a function (event handler) to an HTML element, so that it runs when a specified
event (like click, mouseover, etc.) occurs.

element.addEventListener("event", function);

🔹 Example:

<button id="btn">Click</button>

<script>

document.getElementById("btn").addEventListener("click", function() {

alert("Hello from addEventListener!");

});

</script>

 ✅ Event Propagation in JavaScript

 When an event occurs on a nested element, it travels through the DOM in three phases:

 Capturing Phase (top to target): The event travels down the DOM tree from the window to
the target element.

 Target Phase (event reaches actual target): The event reaches the target element where it
was originally triggered.

 Bubbling Phase (target to top): The event travels back up the DOM tree from the target
element to the root (window).

 ✅ Event Delegation

 A technique where you add one event listener to a parent, and handle events on its children
using event bubbling

 Example:

 js

 Copy code

 document.getElementById("list").addEventListener("click", function(e) {

 if (e.target.tagName === "LI") {

 alert("Clicked: " + e.target.innerText);

 }

 });
 ✅ Improves performance and handles dynamically added elements.

 ✅ Preventing Default Behavior

 Used to stop the browser's default action (e.g., form submit, link redirect).

 js

 Copy code

 document.querySelector("form").addEventListener("submit", function(e) {

 e.preventDefault(); // Prevent form from submitting

 });

 ✅ What is an Event Loop in JavaScript?

 JavaScript is single-threaded, but it uses an event loop to handle asynchronous operations.

 Working:

 Stack handles sync code.

 Web APIs handle async tasks (e.g., setTimeout, fetch).

 Queue stores completed async tasks.

 Event Loop pushes tasks from the queue to the stack when it's empty.

 ✅ Event Bubbling in JavaScript

 In event bubbling, the event is first captured and handled by the target element, and then it
bubbles up to parent elements.

 Example:

 js

 Copy code

 document.getElementById("child").addEventListener("click", () => alert("Child"));

 document.getElementById("parent").addEventListener("click", () => alert("Parent"));

 Clicking the child will alert:

 Child

 Parent

 ✅ How Event Bubbling Works

 Event occurs on a nested element.

 Event handled by the target.

 Then travels up through its parents.

 ✅ How to Stop Event Bubbling

 Use event.stopPropagation():

 js

 Copy code

 child.addEventListener("click", function(e) {

 e.stopPropagation();

 alert("Child only");

 });

 ✅ Advantages of Event Bubbling

 Better performance with event delegation.

 Easy to manage multiple events from one place.

 Useful for dynamically created elements.

 ✅ Event Bubbling vs Event Capturing

 Event bubbling is the default behaviour where an event start from


innermost element and bubbles upto the root. Useful for handling
events at higher level

 Event capturing is when the event captured at the outermost element and bubbles down
to the target.

 Feature  Bubbling  Capturing

 Order  Child to parent  Parent to child


 Feature  Bubbling  Capturing

 Default
 Yes  Needs third param (true)
phase

 addEventListener(event, fn,
 Syntax  addEventListener(event, fn)
true)

 Commonly used (e.g.,


 Use case  Rarely used
delegation)

Numbers

 JavaScript has a single Number type for all numeric values (both integers and floats).

 Supports operations: +, -, *, /, %, and many math functions via Math object.

Example:

let x = 42;

let y = 3.14;

console.log(x + y); // 45.14

String

 Immutable sequence of characters.

 Supports concatenation (+), slicing, searching, and many methods


like .toUpperCase(), .slice(), .replace(), .split(), etc.

Example:

let str = "Hello World";

console.log(str.toLowerCase()); // "hello world"

console.log(str.slice(0,5)); // "Hello"

Array

 Ordered, indexed collection of elements.

 Dynamic size, stores any types.

 Useful methods: .push(), .pop(), .shift(), .unshift(), .slice(), .splice(), .map(), .filter(), .reduce()

 Mutating elements : push(),pop(),shift(),unshift(),splice()

 Non mutating elements: slice(),map(),filter(),reduce()


push()

 Definition: Adds one or more elements to the end of an array.


 let arr = [1, 2];

 arr.push(3); // arr becomes [1, 2, 3]

pop()

 Definition: Removes the last element from an array.


 let arr = [1, 2, 3];

 arr.pop(); // returns 3, arr becomes [1, 2]

shift()

 Definition: Removes the first element from an array.


 let arr = [1, 2, 3];

 arr.shift(); // returns 1, arr becomes [2, 3]

unshift()

 Definition: Adds one or more elements to the beginning of an array.


 let arr = [2, 3];

 arr.unshift(1); // arr becomes [1, 2, 3]

splice(start, deleteCount, item1, item2, ...)

 Definition: Adds/removes elements at a specified index.


 let arr = [1, 2, 3];

 arr.splice(1, 1, 4); // arr becomes [1, 4, 3]

slice(start, end)

 Definition: Returns a shallow copy of a portion of an array from start to end


(excluding end).
 let arr = [1, 2, 3, 4];

 arr.slice(1, 3); // returns [2, 3]

map(callback)

 Definition: Creates a new array by applying the callback function to each element
of the array.
 let arr = [1, 2, 3];

 arr.map(x => x * 2); // returns [2, 4, 6]

filter(callback)
 Definition: Creates a new array with all elements that pass the test in the callback
function.
 let arr = [1, 2, 3, 4];

 arr.filter(x => x % 2 === 0); // returns [2, 4]

reduce(callback, initialValue)

 Definition: Applies a function against an accumulator and each element of the array
(from left to right) to reduce it to a single value.
 let arr = [1, 2, 3, 4];

 arr.reduce((acc, curr) => acc + curr, 0); // returns 10

  Use map() when you want to change or transform every element.


  Use filter() when you want to remove some elements based on a condition.

LinkedList

A linked list is a linear data structure where elements are stored in nodes, each containing a value
and a reference (or pointer) to the next node. It allows for efficient insertion and deletion
operations.

 Not native to JavaScript; you implement it manually.

 Nodes linked by references, good for efficient insertions/deletions.

 Example: singly or doubly linked list.

Simple singly linked list node structure:

class Node {

constructor(value) {

this.value = value;

this.next = null;

Map

A Map is a data structure that stores key-value pairs, where each key is unique.

 Key-value collection, keys can be any type (including objects).

 Iterates in insertion order.

 Creatig a map

 let myMap = new Map();


 let anotherMap = new Map([

 ['name', 'GFG'],

 ['age', 30],

 ['city', 'Noida']

 ]);

 console.log(anotherMap);

 Has .set(), .get(), .has(), .delete() methods.

 Properties of JavaScript Map

 set(key, val) : Adds or updates an element with a specified key and value.

 get(key) : Returns the value associated with the specified key.

 has(key) : Returns a boolean indicating whether an element with the specified key exists.

 delete(key) : Removes the element with the specified key.

 clear(): Removes all elements from the Map.

 size: Returns the number of key-value pairs in the Map.

Example:

let map = new Map();

map.set('name', 'Alice');

console.log(map.get('name')); // Alice

Stack

 LIFO (Last In First Out) data structure.

 Can be implemented using arrays: push/pop.

Push: Adds an element to the top of the stack.



 Pop: Removes and returns the top element from the
stack.
Stack Underflow:
 Occurs when you try to perform a pop or peek operation
on an empty stack.
Stack Overflow:
 Occurs when you try to push an element into a stack that
has reached its maximum capacity
 Operations Performed on a Stack
 Push: Adds an element to the top of the stack.
 Pop: Removes and returns the top element from the
stack.
 Peek (or Top): Returns the top element without
removing it.
 isEmpty: Checks if the stack is empty.
 Size: Returns the number of elements in the stack.

Example:

let stack = [];

stack.push(1);

stack.push(2);

console.log(stack.pop()); // 2

Queue

A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are
inserted at the rear and removed from the front.

 FIFO (First In First Out) data structure.

 Can be implemented with arrays: push (enqueue), shift (dequeue).

 Queue Operations

 enqueue(item) - Adds an element to the end of the queue.

 dequeue() - Removes and returns the first element from the queue.

 peek() - Returns the first element without removing it.

 isEmpty() - Checks if the queue is empty.

 size() - Returns the number of elements in the queue.

 clear() - Removes all elements from the queue.

 print() - Prints the elements of the queue.

Example:

let queue = [];

queue.push(1);

queue.push(2);

console.log(queue.shift()); // 1

Sorting Algorithms
Common sorting algorithms:

 Bubble Sort: repeatedly swaps adjacent elements if in wrong order (O(n²))

 Selection Sort: selects the minimum element and swaps (O(n²))

 Insertion Sort: builds sorted array one element at a time (O(n²))

 Merge Sort: divides array, sorts, merges (O(n log n))

 Quick Sort: divides using a pivot, sorts recursively (average O(n log n))

 Heap Sort: uses heap data structure (O(n log n))

Example (Bubble Sort):

function bubbleSort(arr) {

let n = arr.length;

for(let i = 0; i < n; i++) {

for(let j = 0; j < n - i - 1; j++) {

if(arr[j] > arr[j+1]) {

[arr[j], arr[j+1]] = [arr[j+1], arr[j]];

return arr;

console.log(bubbleSort([5,3,8,4,2])); // [2,3,4,5,8]

If you want, I can explain any of these in more depth or provide implementations!

Here’s a quick explanation of each:

WeakMap

 A collection of key-value pairs where keys must be objects.

 Values can be of any type.

 WeakMap does not support iteration (e.g., keys(), values(), forEach()).

 It does not have a size property.

Example:
let wm = new WeakMap();

let obj = {};

wm.set(obj, 'metadata');

console.log(wm.get(obj)); // 'metadata'

// if obj is dereferenced, it can be GC'd

WeakSet

 A collection of unique objects.

 Similar to WeakMap, it uses weak references, so stored objects can be garbage collected if
they are not referenced elsewhere.

 WeakSet does not support iteration (e.g., keys(), values(), forEach()) or a size property.

Example:

let ws = new WeakSet();

let obj = {};

ws.add(obj);

console.log(ws.has(obj)); // true

Typed Arrays

 Arrays for binary data with fixed size and type.

 Provide views on ArrayBuffer to manipulate raw binary data.

 Examples: Int8Array, Uint8Array, Float32Array, etc.

 Useful for performance-critical tasks like WebGL, image processing, networking.

Example:

let buffer = new ArrayBuffer(8);

let view = new Uint8Array(buffer);

view[0] = 255;

console.log(view[0]); // 255

Deque (Double-Ended Queue)

 Data structure where you can add or remove elements at both front and back.
 JavaScript doesn’t have a built-in Deque, but you can implement it using arrays efficiently
using .push(), .pop(), .shift(), .unshift().

 Useful for sliding window algorithms, task scheduling, etc.

Priority Queue (Heap)

 Data structure where elements are processed by priority, not just order of insertion.

 Usually implemented using a heap (binary heap).

 No native JavaScript PriorityQueue, but you can implement or use libraries.

 Common in scheduling, graph algorithms (Dijkstra’s), etc.

Simple idea of a min-heap-based priority queue:

 Insert elements keeping heap property.

 Extract minimum element efficiently.

Introduction to OOP

OOP is a programming paradigm based on the concept of objects which can contain data and
methods. It helps organize code by modeling real-world entities.

Objects

 An object is a collection of key-value pairs.

 Values can be properties or methods.

Example:

let person = {

name: "Alice",

age: 25,

greet() {

console.log("Hello, " + this.name);

};

person.greet(); // Hello, Alice


Classes

 ES6 introduced class syntax as a blueprint for creating objects.

 Classes encapsulate data (properties) and behavior (methods).

Example:

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

greet() {

console.log("Hi, I'm " + this.name);

let p = new Person("Bob", 30);

p.greet(); // Hi, I'm Bob

Constructor Method

 Special method for creating and initializing objects.

 Called automatically when creating an instance with new.


Creating Constructor Functions

 A constructor function is used to create multiple objects with the same properties and
methods.

 js

 Copy code

 function Person(name, age) {

 this.name = name;

 this.age = age;

 }

 const p1 = new Person("Asiya", 22);


 Use new keyword to create an instance.

this Keyword

 Refers to the current object instance inside methods and constructors.

Prototype

In JavaScript, every object has a hidden property called [[Prototype]] (or __proto__) which points
to another object.
That object is called its prototype, and it contains shared methods and properties.

Example:

Person.prototype.sayAge = function() {

console.log(`I'm ${this.age} years old`);

};

p.sayAge(); // I'm 30 years old

Adding Method to Prototype

To avoid duplicating methods for every object instance, add them to the prototype:

js

Copy code

Person.prototype.greet = function() {

console.log("Hello, " + this.name);

};

p1.greet(); // Hello, Asiya

✅ Prototype Inheritance

Prototype inheritance means that objects in JavaScript can inherit properties and methods from
another object via the prototype chain.

You can make one constructor inherit from another:

js

Copy code
function Animal(name) {

this.name = name;

Animal.prototype.speak = function() {

console.log(this.name + " makes a sound");

};

function Dog(name) {

Animal.call(this, name); // Inherit properties

Dog.prototype = Object.create(Animal.prototype); // Inherit methods

Dog.prototype.constructor = Dog;

const dog = new Dog("Tommy");

dog.speak(); // Tommy makes a sound

✅ Prototype Chain in JavaScript

A Prototype Chain is the chain of objects linked through their [[Prototype]] (or __proto__) used to
look up properties and methods.

Every JS object has a hidden [[Prototype]] (proto) which links to another object → forming a chain.

js

Copy code

const obj = {};

console.log(obj.__proto__ === Object.prototype); // true

Chain:
Object → Object.prototype → null
Array → Array.prototype → Object.prototype → null

Static Methods

 Methods defined with static keyword.

 Belong to the class itself, not to instances.


Example:

class MathUtils {

static add(a, b) {

return a + b;

console.log(MathUtils.add(5, 7)); // 12

Use Cases of Static Methods in JavaScript

Static methods are called on the class itself, not on instances of the class. They are typically used for
utility, helper, or factory functions that are related to the class but don’t need access to instance
data.

🔹 1. Utility/Helper Functions

Used for operations that don’t depend on instance state.

js

Copy code

class MathUtils {

static square(n) {

return n * n;

console.log(MathUtils.square(5)); // 25

🔹 2. Factory Methods (Object Creation)

Return customized instances of a class.

js

Copy code

class User {

constructor(name, role) {

this.name = name;
this.role = role;

static createAdmin(name) {

return new User(name, "admin");

const admin = User.createAdmin("Asiya");

console.log(admin); // { name: 'Asiya', role: 'admin' }

🔹 3. Singleton Pattern

Static method ensures only one instance of a class is created.

js

Copy code

class Singleton {

static instance;

static getInstance() {

if (!Singleton.instance) {

Singleton.instance = new Singleton();

return Singleton.instance;

const obj1 = Singleton.getInstance();

const obj2 = Singleton.getInstance();

console.log(obj1 === obj2); // true

🔹 4. Shared Configuration or Constants


Used to store or access values common to all instances.

js

Copy code

class Config {

static apiKey = "123456";

static getApiKey() {

return Config.apiKey;

console.log(Config.getApiKey()); // "123456"

🔹 5. Data Validation or Processing

Useful for validating inputs before object creation.

js

Copy code

class Validator {

static isEmail(email) {

return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

console.log(Validator.isEmail("[email protected]")); // true

🔹 Summary

Use Case Description

Utility functions Common calculations or logic

Factory methods Create and return configured instances

Singleton pattern Restrict object creation to a single instance

Shared configuration Static data accessible to all instances

Input/data validation Check data before use


Use Case Description

Inheritance

 Mechanism to create a new class based on an existing one.

 New class inherits properties and methods from parent.

Example:

class Employee extends Person {

constructor(name, age, salary) {

super(name, age); // call parent constructor

this.salary = salary;

showSalary() {

console.log(`Salary: $${this.salary}`);

let emp = new Employee("Jane", 28, 50000);

emp.greet(); // Hi, I'm Jane

emp.showSalary(); // Salary: $50000

Encapsulation

 Wrapping data (variables) and methods that manipulate them within a class.

 Use private fields (using # prefix) to hide data from outside access.

Example:

class BankAccount {

#balance = 0; // private field

deposit(amount) {
if (amount > 0) this.#balance += amount;

getBalance() {

return this.#balance;

const acc = new BankAccount();

acc.deposit(1000);

console.log(acc.getBalance()); // 1000

// console.log(acc.#balance); // Error: private field

Abstraction

 Hiding internal implementation details and showing only functionality.

 Achieved by defining clear methods to interact with data without exposing inner workings.

 ✅ 3. Abstraction using Classes and Private Fields (ES6+)


 js
 CopyEdit
 class Student {
 #marks; // private field

 constructor(name, marks) {
 this.name = name;
 this.#marks = marks;
 }

 getDetails() {
 return `${this.name} scored ${this.#marks} marks.`;
 }
 }

 const asiya = new Student("Asiya", 95);
 console.log(asiya.getDetails()); // ✅ works
console.log(asiya.#marks); // ❌ Error: Private field
✅ The private field #marks is hidden from outside — true abstraction.

Method Description
Function Hides logic inside function calls
Closures Keeps variables private using scope
Class + #fields ES6+ syntax for true private properties
Polymorphism

 Ability of different classes to be treated through the same interface.

 Methods with the same name behave differently based on the object.

Example:

class Animal {

speak() {

console.log("Animal makes a sound");

class Dog extends Animal {

speak() {

console.log("Woof!");

class Cat extends Animal {

speak() {

console.log("Meow!");

let animals = [new Dog(), new Cat()];

animals.forEach(a => a.speak()); // Woof! Meow!

Getters and Setters

 Special methods to get or set the value of a property.

 Useful for encapsulation and validation.

Example:
class Person {

constructor(name) {

this._name = name; // convention: _property for private-ish

get name() {

return this._name;

set name(value) {

if (value.length > 0) this._name = value;

else console.log("Invalid name");

let p = new Person("John");

console.log(p.name); // John

p.name = ""; // Invalid name

Browser Object Model (BOM)

 BOM provides objects that allow interaction with the browser outside of the webpage
content.

 It includes objects like:

o window (represents browser window)

o navigator (browser info)

o screen (screen info)

o history (browser history)

o location (URL info)

o alert(), confirm(), prompt() (dialog boxes)

Use: To control browser window, navigation, and other browser-level features.

Example:
alert("Hello from BOM!");

console.log(window.location.href);

window.history.back();

✅ Browser Object Model (BOM) Types

BOM lets JavaScript interact with the browser (outside the HTML page).

Key BOM Objects:

 window

 navigator

 screen

 location

 history

 alert, confirm, prompt

✅ Key Features of the BOM

 No official standards (unlike DOM)

 Allows control of the browser window and environment

 Supports popups, redirects, and browser details

js

Copy code

alert("Hello from BOM!");

console.log(window.location.href);

Document Object Model (DOM)

 DOM is a programmatic representation of the HTML document as a tree structure.

 Represents HTML elements as objects (nodes) that can be manipulated dynamically.

 Allows access to elements, attributes, and content of a webpage.

Example:

// Select element by id and change content

document.getElementById("myDiv").innerText = "Updated Text";

// Create new element and add to DOM


let p = document.createElement("p");

p.textContent = "New paragraph";

document.body.appendChild(p);

✅ Features of JavaScript DOM

 Enables dynamic content manipulation

 Events, traversal, and updates to the document

✅ Advantages of Using the DOM with JavaScript

 Dynamically update content without reloading

 Respond to user interactions

 Real-time UI updates

 Form validation and interaction

 Interact with external APIs

✅ Accessing Elements in the DOM

document.getElementById("id"); Selects a single element with the specified id.

document.getElementsByClassName("class"); Selects all elements with the specified class name.

document.querySelector(".class"); Selects the first matching element for the given CSS selector (like
class, id, tag, etc.).

document.querySelectorAll("div"); Selects all elements that match the given CSS selector (in this
case, all <div> elements).

✅ Traversing the DOM

Traversal Usage

parentNode Get parent

childNodes Get children (includes text)

children Only element children

nextSibling Get next node

previousElementSibling Previous element only


Manipulate DOM Elements

 Access elements using selectors (getElementById, querySelector, etc.)

 Change content (innerText, innerHTML)

 Change styles (style property)

 Add/remove elements (appendChild, removeChild)

 Modify attributes (setAttribute, getAttribute)

Example:

let btn = document.querySelector("button");

btn.style.backgroundColor = "blue";

btn.setAttribute("disabled", true);

Event Handling in the DOM

 You can listen and respond to user actions or browser events using event listeners.

 Events include clicks, mouse movements, keypresses, form submissions, etc.

Example:

document.getElementById("myBtn").addEventListener("click", function() {

alert("Button clicked!");

});

BOM vs DOM

Feature BOM DOM

Interact with browser (window, history, Interact with webpage content (HTML
Purpose
location) elements)

Objects window, navigator, screen, history,


document, Element, Node
involved location

Browser window, navigation, alerts,


Controls HTML elements, structure, content
screen

If you want, I can provide code demos or explain how to use BOM and DOM in more detail!

Here’s a clear breakdown of Asynchronous JavaScript concepts: Callbacks, Promises, Promise


Chaining, and Async/Await.
1. Asynchronous JavaScript

What is Asynchronous JavaScript?

JavaScript is single-threaded, but asynchronous operations like setTimeout, fetch, event listeners,
and promises allow non-blocking code execution.

Example:

js

Copy code

console.log("Start");

setTimeout(() => {

console.log("Async Task");

}, 1000);

console.log("End");

Output:

sql

Copy code

Start

End

Async Task

Asynchronous tools in JS:

 setTimeout, setInterval

 AJAX / fetch

 Here are the simple definitions and usage of setTimeout, setInterval, and AJAX / fetch in
JavaScript:

 ⏳ setTimeout()

 Definition:
Executes a function once after a specified delay (in milliseconds).

 Syntax:

 setTimeout(function, delay);

 Example:
 setTimeout(() => {

 console.log("Hello after 2 seconds");

 }, 2000); // runs after 2 seconds

 🔁 setInterval()

 Definition:
Executes a function repeatedly at a specified interval (in milliseconds).

 Syntax:

 setInterval(function, interval);

 Example:

 setInterval(() => {

 console.log("This prints every 1 second");

 }, 1000); // runs every 1 second

 🌐 AJAX (Asynchronous JavaScript and XML)

 XML: Extensible Markup Language (XML) lets you define and store
data in a shareable manner. XML supports information exchange
between computer systems such as websites, databases, and
third-party applications.

 Asynchronous JavaScript refers to the ability of JavaScript to perform tasks


in the background (like fetching data or waiting for a timer) without
blocking the rest of the code from running.
 Common modern method: fetch()

 📡 fetch()

 Definition:
The modern way to make asynchronous HTTP requests (GET, POST, etc.) in JavaScript.

 Syntax:

 fetch(url)

 .then(response => response.json())

 .then(data => console.log(data))

 .catch(error => console.error("Error:", error));

 Example:

 fetch("https://api.example.com/data")
 .then(res => res.json())

 .then(data => console.log(data));

setTimeout() runs a function once after a specified delay (in milliseconds)

🔹 Syntax:
setTimeout(function, delay)

🔹 Example:
setTimeout(() => {
console.log("Hello Asiya!");
}, 2000); // runs after 2 seconds
setInterval() runs a function repeatedly at a fixed time interval (in milliseconds).

🔹 Syntax:

setInterval(function, interval)

🔹 Example:

setInterval(() => {

console.log("Repeating every 1 second");

}, 1000); // runs every 1 second

2. Callbacks

 A callback is a function passed as an argument to another function, which gets called after
some operation completes.

 Used traditionally for async operations.

Example:

function fetchData(callback) {

setTimeout(() => {

callback("Data received!");

}, 1000);

fetchData(function(message) {

console.log(message); // Logs after 1 second

});

Drawback: Callback Hell — nested callbacks become hard to read and maintain.
4. Promises

A Promise is an object that represents the result of an async operation – either success or
failure.

🔹 States of a Promise:

 Pending – not finished

 Resolved – successful

 Rejected – failed

🔹 Example:

js

CopyEdit

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

let success = true;

if (success) {

resolve("Task done!");

} else {

reject("Task failed.");

});

promise

.then(result => console.log(result)) // if resolved

.catch(error => console.error(error)); // if rejected

5. Promise Chaining
A Promise chain is a way to run multiple asynchronous tasks one after another,
using .then() for each step.
Each .then() waits for the previous Promise to resolve.

.then()

 Definition:
Used to handle the success result of a Promise.

.catch()
 Definition:
Used to handle errors or rejections in a Promise.

Example:

new Promise((resolve) => {

setTimeout(() => resolve(1), 1000);

})

.then((result) => {

console.log(result); // 1

return result * 2;

})

.then((result) => {

console.log(result); // 2

return result * 3;

})

.then((result) => {

console.log(result); // 6

});

5. Async/Await

async and await are modern keywords in JavaScript used to write asynchronous code that looks
and behaves like synchronous code, making it easier to read and manage.

1. async Function

async is a keyword used before a function to tell JavaScript that the function will return a Promise
and may contain asynchronous code.

javascript

Copy code

async function myFunction() {

return "Hello";

myFunction().then(result => console.log(result)); // Hello


🕒 2. await Keyword

await is a keyword used inside an async function to make JavaScript wait for a Promise to finish
before moving to the next line.

javascript

Copy code

async function getData() {

let response = await fetch("https://api.example.com/data");

let data = await response.json();

console.log(data); // Output: JSON data

Example:

function delay(ms) {

return new Promise(resolve => setTimeout(resolve, ms));

async function asyncExample() {

console.log("Start");

await delay(1000);

console.log("After 1 second");

await delay(1000);

console.log("After 2 seconds");

asyncExample();

What is JSON?

✅ JSON – JavaScript Object Notation

📖 Definition:
JSON is a lightweight data format used to store and exchange data between systems (like between
a frontend and a backend).
It is easy to read and write, especially for JavaScript users.
🧾 JSON Looks Like This:

"name": "Asiya",

"age": 22,

"isStudent": true,

"skills": ["JavaScript", "HTML", "CSS"]

🔸 JSON uses key-value pairs


🔸 Keys are always in double quotes
🔸 Values can be strings, numbers, booleans, arrays, or even other objects

🆚 JavaScript Object vs JSON

JavaScript Object JSON

Keys can be unquoted Keys must be in quotes

Can contain functions ❌ Functions not allowed

Loosely formatted Strictly formatted

🔁 Converting Between JSON and JS

✅ Convert javascrpt Object to JSON (String):

let person = { name: "Asiya", age: 22 };

let jsonString = JSON.stringify(person);

console.log(jsonString); // {"name":"Asiya","age":22}

✅ Convert JSON to Object:

let jsonStr = '{"name":"Asiya","age":22}';

let obj = JSON.parse(jsonStr);

console.log(obj.name); // Asiya

✅ Where is JSON Used?

 Sending data from client to server or API responses

 Saving settings in configuration files


 Working with APIs like fetch()

✅ What is fetch() in JavaScript?

📖 Definition:

fetch() is a built-in JavaScript function used to get data from a server or a file (like JSON, API, etc.)

It is used to send HTTP requests (like GET, POST) and get responses.

🌐 Example with Fetch API:

fetch("https://api.example.com/user")

.then(response => response.json())

.then(data => {

console.log(data.name);

})

.catch(error => {

console.error("Error fetching data:", error);

});

✅ Code Explanation Table

Line of Code Explanation

Sends a request to the given API URL to get


fetch("https://api.example.com/user")
user data.

Converts the response (which is in JSON


.then(response => response.json())
format) into a JavaScript object.

Accesses the data and logs the user's name


.then(data => { console.log(data.name); })
property to the console.

.catch(error => { console.error("Error fetching If any error occurs (network issue, wrong URL,
data:", error); }) bad JSON), it logs the error.

✅ What are Regular Expressions?

Regex (short for Regular Expression) is a powerful pattern-matching tool used to search, match,
and manipulate text based on specific patterns.

Sure! Here's a simple and clear explanation of Regular Expressions (RegEx) in JavaScript ✅
✅ What is RegEx?

RegEx (Regular Expression) is a pattern used to match text — like checking if a string contains
numbers, emails, or specific formats.

🧪 Basic Syntax

let pattern = /abc/;

let result = pattern.test("abcdef"); // true

 /abc/ → This is the pattern

 .test(string) → Returns true if the pattern matches, else false

📌 RegEx Examples

Pattern Meaning Example Match

/[0-9]/ Any digit "abc3def" → ✅

/[a-z]/ Any lowercase letter "Hello" → ✅ (e)

/[A-Z]/ Any uppercase letter "Test" → ✅ (T)

/\d/ Shortcut for digit [0-9] "123" → ✅

/\w/ Word character (a-z, A-Z, 0-9) "abc_123" → ✅

/\s/ Whitespace (space, tab, etc) "hi there" → ✅

/^abc/ Starts with abc "abcdef" → ✅

/xyz$/ Ends with xyz "helloxyz" → ✅

/a+b/ One or more a followed by b "aaab" → ✅

🔄 Methods to Use RegEx

1. test() – Checks if match exists (true/false)

let pattern = /\d/;

console.log(pattern.test("Age: 25")); // true

2. match() – Returns matching parts

let str = "Price is $100";

console.log(str.match(/\d+/)); // ["100"]

3. replace() – Replaces matched text

let str = "I love cats";


let newStr = str.replace(/cats/, "dogs");

console.log(newStr); // I love dogs

✉️RegEx to Validate Common Inputs

Use Case RegEx Pattern

Email /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/

Phone (10 digit) /^\d{10}$/

Only letters /^[A-Za-z]+$/

Password (min 8 char, 1 number) /^(?=.*\d).{8,}$/

📌 Example: Validate Email

let email = "[email protected]";

let pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

console.log(pattern.test(email)); // true

✅ Regex in JavaScript

let regex = /^[a-zA-Z0-9]+$/; // Alphanumeric only

let result = regex.test("abc123"); // true

✅ Form Validation Fields

1. Email Validation

Regex:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/;

Example:

console.log(emailRegex.test("[email protected]")); // true

2. Number Validation (Only Digits)

Regex:

const numberRegex = /^[0-9]+$/;

Example:

console.log(numberRegex.test("123456")); // true
console.log(numberRegex.test("123abc")); // false

3. Password Validation

Criteria:

 At least one uppercase letter

 At least one lowercase letter

 At least one number

 At least one special character

 Minimum 8 characters

Regex:

const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=!]).{8,}$/;

Example:

console.log(passwordRegex.test("StrongP@ss1")); // true

4. URL Validation

Regex:

const urlRegex = /^(https?:\/\/)?([\w-]+\.)+[\w-]{2,}(\/\S*)?$/;

Example:

console.log(urlRegex.test("https://example.com")); // true

console.log(urlRegex.test("example")); // false

5. Username Validation

Criteria:

 Alphanumeric characters and underscores

 3 to 16 characters

Regex:

const usernameRegex = /^[a-zA-Z0-9_]{3,16}$/;

Example:

console.log(usernameRegex.test("user_123")); // true

console.log(usernameRegex.test("us")); // false (too short)


✅ How to Use in HTML + JavaScript Form

<form onsubmit="return validateForm()">

<input type="text" id="email" placeholder="Email" />

<input type="text" id="username" placeholder="Username" />

<input type="password" id="password" placeholder="Password" />

<button type="submit">Submit</button>

</form>

<script>

function validateForm() {

const email = document.getElementById("email").value;

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

const password = document.getElementById("password").value;

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/;

const usernameRegex = /^[a-zA-Z0-9_]{3,16}$/;

const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=!]).{8,}$/;

if (!emailRegex.test(email)) {

alert("Invalid Email!");

return false;

if (!usernameRegex.test(username)) {

alert("Invalid Username!");

return false;

if (!passwordRegex.test(password)) {

alert("Invalid Password!");

return false;

alert("All validations passed!");


return true;

</script>

✅ Exception and Error Handling in JavaScript

JavaScript uses try-catch-finally blocks to handle runtime errors.

🟠 What is an Exception?

An exception is an abnormal condition or error that occurs during the execution of a program (e.g.,
accessing a property on undefined).

🔹 throw Statement The throw statement is used to manually create (or throw) an error in
JavaScript.
When an error is thrown, the program stops running unless the error is caught using try...catch.

Used to manually throw an exception (custom or built-in).

throw new Error("Something went wrong");

throw "Custom error message"; // not recommended (throws a string)

🔹 try-catch Statement

Wrap code that may fail in a try block, and handle the error in the catch.

try {

let result = riskyFunction(); // may throw error

console.log("Result:", result);

} catch (error) {

console.error("Caught Error:", error.message);

✅ error is an object with properties like:

 error.name

 error.message

 error.stack

🔹 finally Block
Runs after try or catch, always—used for cleanup operations.

try {

// some risky code

} catch (e) {

console.error(e);

} finally {

console.log("This always runs");

✅ Example

function divide(a, b) {

if (b === 0) throw new Error("Cannot divide by zero!");

return a / b;

try {

let result = divide(10, 0);

console.log(result);

} catch (e) {

console.log("Error:", e.message);

} finally {

console.log("End of division");

Output:

Error: Cannot divide by zero!

End of division

🔍 Debugging in JavaScript

Debugging is the process of finding and fixing errors (bugs) in your code to make sure it works as
expected.
JavaScript provides several tools for debugging:

🔸 console Methods:

 console.log() – for general logging

 console.error() – for errors

 console.warn() – for warnings

 console.table() – for tabular data

🔸 Browser DevTools:

 Open F12 or Right-click > Inspect > Console

 Use Breakpoints, Watch, Call Stack, etc.

🔸 debugger Statement:

Pauses execution in DevTools at that line.

function calculate() {

let x = 10;

debugger; // pauses here if DevTools is open

return x * 2;

calculate();

✅ Testing and Performance Optimization in JavaScript

🧪 1. Unit Testing with Jest

Jest is a popular testing framework for JavaScript, mainly used with React but also works with any JS
code.

Features:

 Zero config

 Snapshot testing

 Mocking support

 Parallel test execution

Example:

// sum.js

function sum(a, b) {

return a + b;
}

module.exports = sum;

// sum.test.js

const sum = require('./sum');

test('adds 2 + 3 to equal 5', () => {

expect(sum(2, 3)).toBe(5);

});

Run with:

npx jest

🧠 2. Memory Management in JavaScript

Garbage Collection:

Garbage Collection is the process of automatically identifying and freeing up memory that is no
longer being used by the program.

🔹 Garbage Collector:

A Garbage Collector (GC) is a built-in program or mechanism in the runtime environment (like Java
Virtual Machine (JVM) or JavaScript engine) that performs garbage collection.

JavaScript manages memory automatically via Garbage Collection (GC).

 Stack: Stores function calls, primitives

 Heap: Stores objects and functions

♻️3. Garbage Collection

The JavaScript engine frees memory that's no longer referenced.

Algorithms used:

 Mark-and-Sweep: Marks reachable values and sweeps the rest.

 Generational GC: Optimizes short-lived vs long-lived objects.

Memory leaks: A memory leak occurs when a computer program allocates memory but fails to
release it when it's no longer needed.

Tip: Avoid memory leaks by:


 Use let or const, avoid var

 Always remove event listeners when no longer needed

 Clear timers and intervals

 Avoid global variables and long-lived closures

 Use browser tools like Chrome DevTools → Memory tab to check for leaks

💤 4. Lazy Loading

Load resources only when needed (not at page load).

<img src="image.jpg" loading="lazy" alt="Lazy Image">

In JavaScript:

document.addEventListener('scroll', () => {

if (elementIsVisible(lazyItem)) {

loadComponent();

});

✅ Improves performance by reducing initial page load time.

Both throttling and debouncing are techniques to control the rate at which a function is executed —
especially for events that fire rapidly (like scrolling, resizing, typing, etc.).

⏳ 5. Debouncing

Debouncing means delaying a function call until after a pause in activity. It ensures that the
function runs only once after the user stops doing something (like typing or resizing).

✅ Real-Life Example:

You're searching something in Google. You type:

nginx

CopyEdit

h → he → hel → hell → hello

Without debouncing: It sends 5 API calls (one for each letter typed).
With debouncing: It waits until you stop typing, then sends only 1 API call.
Useful in search input, resize, scroll.

function debounce(fn, delay) {

let timer;

return function (...args) {

clearTimeout(timer);

timer = setTimeout(() => fn.apply(this, args), delay);

};

window.addEventListener('resize', debounce(() => {

console.log('Window resized');

}, 300));

🚦 6. Throttling

Throttling means limiting how often a function can run. Even if the user does something
continuously (like scrolling), the function will run only once every few milliseconds.

✅ Real-Life Example:

You're scrolling a page and you want to check the scroll position.
Without throttling: It fires the scroll event 100s of times per second.
With throttling: It runs, for example, once every 500ms.

Useful in scroll events, mouse movements.

function throttle(fn, limit) {

let inThrottle;

return function (...args) {

if (!inThrottle) {

fn.apply(this, args);

inThrottle = true;

setTimeout(() => (inThrottle = false), limit);

}
};

window.addEventListener('scroll', throttle(() => {

console.log('Scroll event throttled');

}, 200));

📈 Summary Table

Feature Purpose Example Use Case

Jest Unit testing Function/component testing

Memory Mgmt Efficient use of RAM Avoid memory leaks

Garbage Collection Auto cleanup of unused memory Behind the scenes in JS

Lazy Loading Load resources when needed Images/components

Debouncing Limit rapid firing of events Search input

Throttling Limit call rate of function Scroll/resize listeners

Would you like a working mini project to demonstrate these techniques in real time?

You might also like