0% found this document useful (0 votes)
10 views411 pages

Directives in Angular

The document explains the different types of directives in Angular, which include Component Directives for reusable UI elements, Attribute Directives for modifying element behavior, and Structural Directives for altering the DOM structure. It also covers Angular decorators, types of pipes, and the concept of services, including how to create and use them with dependency injection. Additionally, it discusses parent-child component relationships and lifecycle hooks in Angular.

Uploaded by

MERIN SCARIA
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)
10 views411 pages

Directives in Angular

The document explains the different types of directives in Angular, which include Component Directives for reusable UI elements, Attribute Directives for modifying element behavior, and Structural Directives for altering the DOM structure. It also covers Angular decorators, types of pipes, and the concept of services, including how to create and use them with dependency injection. Additionally, it discusses parent-child component relationships and lifecycle hooks in Angular.

Uploaded by

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

Directives in Angular

Difference between Component, Attribute and Structural


Directives?

In Angular, directives are used to extend the behavior of elements and components. There are three
types of directives:

1. Component Directives

2. Attribute Directives

3. Structural Directives

1. Component Directives
A component is a special type of directive that includes a template (HTML), styles, and logic.

It is used to define reusable UI elements.

Every component has a selector, template, and style.

Example:

typescript

@Component({
selector: 'app-example',
template: `<h2>Hello, Angular!</h2>`,
styles: ['h2 { color: blue; }']
})
export class ExampleComponent { }

Key Features:

Has an associated template ( templateUrl or template ).

Used to create reusable UI elements.

Must be declared in an Angular module.

2. Attribute Directives
Modify the appearance or behavior of an element, component, or another directive.

Do not change the structure of the DOM.

Built-in Attribute Directives:

1/411
ngClass – Adds/removes CSS classes dynamically.

ngStyle – Applies inline styles dynamically.

Example:

html

<p [ngClass]="{'text-success': isSuccess, 'text-danger': !isSuccess}">Hello</p>

Custom Attribute Directive:

typescript

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}

Key Features:

Change appearance or behavior of elements.

Used as an attribute in HTML elements.

3. Structural Directives
Modify the structure of the DOM by adding or removing elements.

Always start with * when used in templates.

Built-in Structural Directives:

*ngIf – Adds or removes elements based on a condition.

*ngFor – Repeats an element for each item in a collection.

*ngSwitch – Conditionally renders elements.

Example:

html

2/411
<div *ngIf="isVisible">This text is conditionally visible</div>

Custom Structural Directive:

typescript

@Directive({
selector: '[appIf]'
})
export class CustomIfDirective {
@Input() set appIf(condition: boolean) {
if (!condition) {
this.viewContainer.clear();
} else {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}

constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef)


{}
}

Key Features:

Modify the DOM structure by adding or removing elements.

Used with * before the directive name.

Key Differences at a Glance


Type Purpose Example

Component Creates reusable UI elements with templates and logic <app-example></app-


example>

Attribute Directive Modifies the appearance or behavior of elements [ngClass] , [appHighlight]

Structural Modifies the structure of the DOM (add/remove *ngIf , *ngFor , *appIf
Directive elements)

Would you like more examples or use cases? 😊


Decorator & Pipes - Introduction

Q28. What are the types of Decorator?


Q29. What are Pipes? What are the types of Pipes & Parameterized

3/411
Pipes?
Q30. What is Chaining Pipes?

Q28. What are the types of Decorators in Angular?


In Angular, decorators are special functions that modify classes, methods, properties, or parameters.
They provide metadata and enhance the functionality of Angular elements.

Types of Decorators:

1. Class Decorators

Used to declare and configure classes.

Example: @Component , @Directive , @Injectable , @Pipe

Example (Component Decorator):

typescript

@Component({
selector: 'app-example',
template: `<h2>Hello, Angular!</h2>`
})
export class ExampleComponent { }

2. Property Decorators

Used to define metadata for class properties.

Example: @Input() , @Output()

Example:

typescript

export class ChildComponent {


@Input() dataFromParent!: string;
@Output() eventEmitter = new EventEmitter<string>();
}

3. Method Decorators

Used to enhance methods in a class.

Example: @HostListener()

Example:

typescript

@Directive({
selector: '[appClickListener]'

4/411
})
export class ClickListenerDirective {
@HostListener('click') onClick() {
alert('Element clicked!');
}
}

4. Parameter Decorators

Used to inject dependencies into class constructors.

Example: @Inject() , @Optional()

Example:

typescript

export class ExampleService {


constructor(@Inject(String) private message: string) { }
}

Q29. What are Pipes? What are the types of Pipes & Parameterized Pipes?

Pipes in Angular:

Pipes transform data into a desired format in templates without changing the original data.

Types of Pipes:

1. Built-in Pipes (Predefined in Angular)

DatePipe - Formats date values.

UpperCasePipe - Converts text to uppercase.

LowerCasePipe - Converts text to lowercase.

CurrencyPipe - Formats currency values.

DecimalPipe - Formats decimal numbers.

PercentPipe - Converts numbers to percentages.

SlicePipe - Extracts a portion of an array or string.

JsonPipe - Converts objects to JSON format.

Example:

html

5/411
<p>{{ today | date: 'short' }}</p>
<p>{{ price | currency: 'INR' }}</p>

2. Custom Pipes (User-defined)

Created to implement custom logic.

Example (Creating a Custom Pipe):

typescript

@Pipe({ name: 'reverse' })


export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}

Usage in HTML:

html

<p>{{ 'Angular' | reverse }}</p> <!-- Output: ralugnA -->

Parameterized Pipes:

Some pipes accept parameters for customization.

Example:
html

<p>{{ 3.14159 | number: '1.2-2' }}</p> <!-- Output: 3.14 -->


<p>{{ 'Hello World' | slice: 0:5 }}</p> <!-- Output: Hello -->

Q30. What is Chaining Pipes?


Chaining pipes means applying multiple pipes in sequence.

The output of one pipe becomes the input of the next.

Example:

html

<p>{{ 'angular pipes' | uppercase | slice: 0:7 }}</p>

6/411
Output: ANGULAR

Would you like more detailed examples? 😊


Explain Services in Angular with examples
Q32. How to create Servicein Angular?
03:18
Q33. How to use Dependency Injector with Services in Angular?
01:52
Q34. What is Hierarchical Dependency Injection?
02:39
Q35. What is Provider in Angular?
01:09
Q36. What is the role of @Injectable Decorator in a Service?

Services in Angular

Q31: Explain Services in Angular with examples

In Angular, a service is a reusable class that provides business logic, data handling, and shared
functionality across multiple components.

Why Use Services?

Reusability: Code can be shared across components.

Separation of Concerns: Business logic is separated from UI logic.

Dependency Injection (DI): Services are injected wherever needed.

State Management: Store and manage data across the application.

Example of a Service:

typescript

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root' // Service is available throughout the app
})
export class DataService {
private data: string = 'Angular Service Data';

getData(): string {
return this.data;
}
}

7/411
Using the Service in a Component

typescript

import { Component } from '@angular/core';


import { DataService } from './data.service';

@Component({
selector: 'app-example',
template: `<h2>{{ data }}</h2>`
})
export class ExampleComponent {
data: string;

constructor(private dataService: DataService) {


this.data = this.dataService.getData();
}
}

Q32: How to Create a Service in Angular?


To create a service in Angular, use the Angular CLI:

sh

ng generate service service-name

or

sh

ng g s service-name

Example: Creating a User Service

sh

ng g s user

Generated user.service.ts file:

typescript

8/411
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class UserService {
getUser(): string {
return 'John Doe';
}
}

Q33: How to Use Dependency Injector with Services in Angular?


Dependency Injection (DI) is a design pattern that allows Angular to inject services into components,
directives, or other services.

Steps to Use Dependency Injection:

1. Create a Service (e.g., user.service.ts ).

2. Provide the Service using @Injectable({ providedIn: 'root' }) or manually in providers


array of app.module.ts .

3. Inject the Service into the constructor of a component.

Example: Using DI in a Component

typescript

import { Component } from '@angular/core';


import { UserService } from './user.service';

@Component({
selector: 'app-user',
template: `<p>User: {{ user }}</p>`
})
export class UserComponent {
user: string;

constructor(private userService: UserService) {


this.user = this.userService.getUser();
}
}

9/411
Q34: What is Hierarchical Dependency Injection?
Hierarchical Dependency Injection (DI) is the way Angular manages service instances based on
module and component trees.

Levels of DI:

1. Root Level ( providedIn: 'root' ):

Service is available throughout the application.

Single instance shared across components.

2. Module Level ( providers in a feature module):

Service is provided only within that module.

Components within that module get a separate instance.

3. Component Level ( providers in @Component ):

Service is only available within that component and its children.

Each component gets a new instance.

Example of Component-Level DI

typescript

@Component({
selector: 'app-child',
template: `<p>Child Component</p>`,
providers: [UserService] // Provides a new instance for this component
})
export class ChildComponent {
constructor(private userService: UserService) { }
}

Q35: What is a Provider in Angular?


A provider is an instruction to Angular on how to create and deliver a service.

Types of Providers:

1. Class Provider (default)

typescript

10/411
providers: [UserService]

2. Value Provider

typescript

providers: [{ provide: 'API_URL', useValue: 'https://api.example.com' }]

3. Factory Provider

typescript

providers: [{ provide: UserService, useFactory: () => new UserService() }]

4. Aliased Provider

typescript

providers: [{ provide: DataService, useExisting: UserService }]

Q36: What is the Role of @Injectable Decorator in a Service?


The @Injectable decorator marks a class as an Angular service and allows it to be injected using
Dependency Injection.

Roles of @Injectable :

Tells Angular this class can be injected into other classes.

Allows Angular to manage instances of the service.

Supports hierarchical DI when provided in modules or components.

Example with @Injectable

typescript

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class AuthService {
isAuthenticated(): boolean {
return true;

11/411
}
}

Would you like more details on any specific topic? 😊


Decorators & Lifecycle - Hooks - Introduction
What are parent-child components?
Q38.Define@Input Decorator ?How to transfer data from Parent to
Child component?
05:09
Q39. What is @Output Decorator and Event Emitter?
06:18
Q40. What are Lifecycle Hooks in Angular?
03:25
Q41. What is a Constructor in Angular?
02:18
Q42. What is ngOnChanges life cycle hook in Angular?
04:11
Q43. What is ngOnInit life cycle hook in Angular?
01:26
Q44. What is the difference between constructor and ngOnInit ?

Parent-Child Components in Angular


In Angular, parent-child components refer to a relationship where:

The parent component contains the child component.

The child component receives data or events from the parent.

Communication between them is done using @Input() (for passing data) and @Output() (for
sending events).

Example of Parent-Child Component Communication

Parent Component ( app-parent )

html

<app-child [childMessage]="parentMessage"></app-child>

Child Component ( app-child )

typescript

import { Component, Input } from '@angular/core';

@Component({

12/411
selector: 'app-child',
template: `<p>Message from parent: {{ childMessage }}</p>`
})
export class ChildComponent {
@Input() childMessage!: string; // Receiving data from parent
}

Q38: What is the @Input Decorator? How to transfer data from


Parent to Child Component?
@Input() Decorator

Used to pass data from a parent component to a child component.

Declared in the child component to accept input from the parent.

Example of Data Transfer from Parent to Child

Parent Component

typescript

import { Component } from '@angular/core';

@Component({
selector: 'app-parent',
template: `<app-child [childMessage]="message"></app-child>`
})
export class ParentComponent {
message = 'Hello from Parent!';
}

Child Component

typescript

import { Component, Input } from '@angular/core';

@Component({
selector: 'app-child',
template: `<p>Received: {{ childMessage }}</p>`
})
export class ChildComponent {

13/411
@Input() childMessage!: string;
}

Q39: What is the @Output Decorator and EventEmitter?


@Output() Decorator

Used to send events/data from a child component to a parent component.

Requires EventEmitter to emit events.

Example of Sending Data from Child to Parent

Child Component

typescript

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();

sendMessage() {
this.messageEvent.emit('Hello from Child!');
}
}

Parent Component

typescript

import { Component } from '@angular/core';

@Component({
selector: 'app-parent',
template: `<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>Message: {{ message }}</p>`
})
export class ParentComponent {
message = '';

14/411
receiveMessage(event: string) {
this.message = event;
}
}

Q40: What are Lifecycle Hooks in Angular?


Lifecycle hooks are special methods in an Angular component that execute at specific moments in a
component’s life cycle.

List of Lifecycle Hooks:


Hook Description

ngOnChanges() Called when input properties change.

ngOnInit() Called once after component initialization.

ngDoCheck() Detects custom changes in component state.

ngAfterContentInit() Called after content projection ( <ng-content> ) is initialized.

ngAfterContentChecked() Called after every change detection on projected content.

ngAfterViewInit() Called after component’s view is initialized.

ngAfterViewChecked() Called after every change detection on the component’s view.

ngOnDestroy() Called before the component is destroyed (used for cleanup).

Q41: What is a Constructor in Angular?


Constructor in Angular
A special method that initializes the component class.

Called before the component is created.

Used for dependency injection but should not contain heavy logic.

Example:
typescript

15/411
import { Component } from '@angular/core';

@Component({
selector: 'app-example',
template: `<p>Constructor Example</p>`
})
export class ExampleComponent {
constructor() {
console.log('Constructor called!');
}
}

Q42: What is ngOnChanges Lifecycle Hook?


ngOnChanges()

Called whenever an @Input() property changes.

Used for reacting to changes in parent data.

Example:

typescript

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-child',
template: `<p>Value: {{ value }}</p>`
})
export class ChildComponent implements OnChanges {
@Input() value!: string;

ngOnChanges(changes: SimpleChanges) {
console.log('Changes detected:', changes);
}
}

Q43: What is ngOnInit Lifecycle Hook?

16/411
ngOnInit()

Called once after component initialization.

Used for initial setup, fetching data, or setting default values.

Example:

typescript

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-example',
template: `<p>ngOnInit Example</p>`
})
export class ExampleComponent implements OnInit {
ngOnInit() {
console.log('ngOnInit called!');
}
}

Q44: Difference Between Constructor and ngOnInit


Feature Constructor ngOnInit()

Execution Time Called when the class is Called after the constructor and after component
instantiated. initialization.

Purpose Used for dependency injection. Used for initialization logic (like fetching API data).

Angular Not part of Angular lifecycle. Part of Angular lifecycle hooks.


Lifecycle

Usage Should not include complex logic. Good for API calls, subscriptions, and initialization
logic.

Example Comparison:

typescript

export class ExampleComponent implements OnInit {


constructor() {
console.log('Constructor: Class Initialized!');
}

17/411
ngOnInit() {
console.log('ngOnInit: Component Initialized!');
}
}

Output:

vbnet

Constructor: Class Initialized!


ngOnInit: Component Initialized!

Would you like more detailed examples on any topic? 😊


What is router outlet?
01:17
Q47. What are router links ?

Q46: What is router-outlet in Angular?


The <router-outlet> is a directive used in Angular’s Router Module to act as a placeholder for
dynamically loading components based on the route.

Key Points:
It defines where the routed components should be displayed.

It works with Angular’s Router Module for Single Page Applications (SPA).

You can have multiple router-outlet instances (e.g., for child routes).

Example of Using router-outlet

app.module.ts (Import Router Module)

typescript

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';

const routes: Routes = [

18/411
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' } // Default route
];

@NgModule({
declarations: [AppComponent, HomeComponent, AboutComponent],
imports: [BrowserModule, RouterModule.forRoot(routes)],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html (Using router-outlet )

html

<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<hr>
<router-outlet></router-outlet> <!-- Dynamic component rendering -->

When visiting /home URL, HomeComponent is displayed inside router-outlet .

Q47: What are Router Links in Angular?


Router Links ( routerLink Directive)
routerLink is used to navigate between components without reloading the page.

It replaces the need for <a href="..."> , preventing full-page reloads.

Example of Router Links

html

<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

Active Link Styling


To highlight the active link:

19/411
html

<a routerLink="/home" routerLinkActive="active">Home</a>


<a routerLink="/about" routerLinkActive="active">About</a>

css

.active {
font-weight: bold;
color: blue;
}

Programmatic Navigation Using Router


Instead of <a routerLink> , you can navigate via TypeScript:

typescript

import { Router } from '@angular/router';

constructor(private router: Router) {}

goToHome() {
this.router.navigate(['/home']);
}

Would you like an example of child routing or lazy loading? 😊


Child Routing and Lazy Loading in Angular
Child routing allows nesting routes inside other routes, making complex applications more
manageable. Lazy loading helps optimize performance by loading feature modules only when needed.

1️⃣ Child Routing in Angular


Child routing enables defining routes inside a parent route.

Example: Parent-Child Routing Setup

Step 1: Define Child Routes in a Module

In app-routing.module.ts , define child routes inside the children array.

typescript

20/411
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildOneComponent } from './child-one.component';
import { ChildTwoComponent } from './child-two.component';

const routes: Routes = [


{
path: 'parent',
component: ParentComponent,
children: [
{ path: 'child-one', component: ChildOneComponent },
{ path: 'child-two', component: ChildTwoComponent },
],
},
{ path: '', redirectTo: '/parent', pathMatch: 'full' }, // Default route
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Step 2: Use router-outlet in Parent Component

Inside parent.component.html , place <router-outlet> for rendering child components.

html

<h2>Parent Component</h2>
<nav>
<a routerLink="child-one">Child One</a> |
<a routerLink="child-two">Child Two</a>
</nav>

<!-- Child components will be loaded here -->


<router-outlet></router-outlet>

21/411
Step 3: Child Components

child-one.component.html

html

<h3>Child One Component</h3>

child-two.component.html

html

<h3>Child Two Component</h3>

🔹 Result:
Visiting /parent loads the ParentComponent, and clicking the links loads either ChildOneComponent
or ChildTwoComponent inside the parent.

2️⃣ Lazy Loading in Angular


Lazy loading loads feature modules only when the user navigates to them, improving performance.

Steps for Implementing Lazy Loading

Step 1: Create a Feature Module

Run the command:

sh

ng generate module feature --route=feature --module=app.module

This creates a feature module ( feature.module.ts ) with its own routing.

Step 2: Define Routes in feature-routing.module.ts

Modify the routes to use lazy loading.

typescript

import { NgModule } from '@angular/core';


import { RouterModule, Routes } from '@angular/router';

22/411
import { FeatureComponent } from './feature.component';

const routes: Routes = [


{ path: '', component: FeatureComponent }
];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeatureRoutingModule { }

Step 3: Load the Module Lazily in app-routing.module.ts

Modify app-routing.module.ts to lazy load the module using loadChildren .

typescript

const routes: Routes = [


{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m =>
m.FeatureModule) }
];

🔹 Result:
The feature.module.ts is not loaded initially.

It loads only when the user navigates to /feature , reducing initial load time.

📝 Summary
Feature Purpose

Child Routing Nesting routes inside a parent route ( children: [...] ).

Lazy Loading Loads feature modules only when needed, optimizing performance.

Would you like an example of route guards (authentication-based navigation)? 😊

23/411
Route Guards in Angular (Authentication-Based Navigation)
Route Guards in Angular control access to routes based on conditions, such as authentication or role-
based access.

1️⃣ Types of Route Guards


Angular provides five types of guards:

Guard Purpose

CanActivate Blocks or allows access to a route.

CanActivateChild Blocks or allows access to child routes.

CanDeactivate Prevents navigation away from a route (e.g., unsaved changes warning).

Resolve Fetches data before loading a route.

CanLoad Prevents lazy-loaded modules from being loaded.

For authentication, the most commonly used guards are CanActivate and CanLoad .

2️⃣ Implementing Authentication Using CanActivate

This guard restricts access to a route if the user is not logged in.

Step 1: Create an Auth Service


The Auth Service manages user login state.

typescript

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class AuthService {
private isLoggedIn = false; // Change to true after successful login

login() {
this.isLoggedIn = true;
}

24/411
logout() {
this.isLoggedIn = false;
}

isAuthenticated(): boolean {
return this.isLoggedIn;
}
}

Step 2: Create an Auth Guard


Generate a guard using:

sh

ng generate guard auth

Modify auth.guard.ts to implement CanActivate :

typescript

import { Injectable } from '@angular/core';


import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']); // Redirect to login page
return false;
}
}
}

25/411
Step 3: Protect Routes Using CanActivate
Modify app-routing.module.ts to apply the guard:

typescript

import { NgModule } from '@angular/core';


import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { LoginComponent } from './login.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [


{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, // Protected
route
{ path: 'login', component: LoginComponent }, // Public route
{ path: '', redirectTo: '/login', pathMatch: 'full' } // Default route
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Step 4: Implement Login Logic


Modify login.component.ts to handle authentication:

typescript

import { Component } from '@angular/core';


import { Router } from '@angular/router';
import { AuthService } from './auth.service';

@Component({
selector: 'app-login',
template: `
<h2>Login Page</h2>
<button (click)="login()">Login</button>
`
})
export class LoginComponent {
constructor(private authService: AuthService, private router: Router) {}

26/411
login() {
this.authService.login();
this.router.navigate(['/dashboard']); // Redirect after login
}
}

3️⃣ Prevent Lazy-Loaded Module Access Using CanLoad

CanLoad prevents an entire module from being loaded if the user is not authenticated.

This improves security and performance by preventing unauthorized users from even loading the
code.

Modify auth.guard.ts to include CanLoad :

typescript

import { Injectable } from '@angular/core';


import { CanActivate, CanLoad, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {
constructor(private authService: AuthService, private router: Router) {}

canActivate(): boolean {
return this.checkLogin();
}

canLoad(): boolean {
return this.checkLogin();
}

private checkLogin(): boolean {


if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}

27/411
}
}

Step 5: Protect Lazy-Loaded Modules Using CanLoad


Modify app-routing.module.ts :

typescript

const routes: Routes = [


{ path: 'dashboard', loadChildren: () => import('./dashboard.module').then(m =>
m.DashboardModule), canLoad: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full' }
];

4️⃣ Summary
Feature Purpose

CanActivate Blocks or allows route access based on authentication.

CanLoad Prevents unauthorized users from even loading a module.

Auth Service Manages authentication state ( login() , logout() ).

🔹 Final Flow:
1️⃣ If the user is not logged in, they are redirected to .
/login
2️⃣ After clicking "Login", they are redirected to /dashboard.
3️⃣ If they try to access/dashboard directly without logging in, they are blocked.
4️⃣ If CanLoadis used, lazy modules won't even be downloaded for unauthorized users.

Would you like an example for role-based access (e.g., Admin vs User)? 🚀

Q49. What is the difference between Promise and Observable?


04:27
Q50. What is RxJS?

28/411
02:33
Q51. What is Observable? How to implement Observable ?
04:48
Q52. What is the role of HttpClient in Angular?
01:16
Q53. What are the steps for fetching the data with HttpClient &
Observable ?
08:46
Q54. How to do HTTP Error Handling in Angular ?

Difference Between Promise and Observable (Q49)


Feature Promise Observable

Execution Executes immediately when Executes only when subscribed.


created.

Handling Multiple Returns only one value. Emits multiple values over time.
Values

Cancellation Cannot be canceled once Can be canceled using unsubscribe() .


started.

Operators Supports .then() and Supports powerful RxJS operators like map() ,
.catch() . filter() , retry() , etc.

Use Case Ideal for one-time API calls. Ideal for streams of data, WebSockets, or user events.

🔹 Example of a Promise:
typescript

const myPromise = new Promise((resolve, reject) => {


setTimeout(() => resolve("Data received"), 2000);
});

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

🔹 Example of an Observable:
typescript

import { Observable } from 'rxjs';

const myObservable = new Observable(observer => {


setInterval(() => observer.next("Streaming data..."), 1000);
});

const subscription = myObservable.subscribe(data => console.log(data));

29/411
// Unsubscribe after 5 seconds
setTimeout(() => subscription.unsubscribe(), 5000);

What is RxJS? (Q50)


RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. It
allows handling asynchronous data streams efficiently.

🔹 Key Features:
Provides Observables, Operators, and Subscriptions.

Allows data transformation with operators like map() , filter() , merge() , etc.

Used extensively in HTTP requests, WebSockets, and event handling in Angular.

🔹 Example Using RxJS Operator:


typescript

import { of } from 'rxjs';


import { map } from 'rxjs/operators';

of(2, 4, 6).pipe(map(num => num * 2)).subscribe(result => console.log(result));

Output: 4, 8, 12

What is an Observable? How to Implement Observable? (Q51)


An Observable is a data stream that emits values over time. It requires a subscriber to listen to its
emitted values.

Creating and Using an Observable

typescript

import { Observable } from 'rxjs';

const myObservable = new Observable(observer => {


observer.next("Value 1");
observer.next("Value 2");
setTimeout(() => observer.next("Value 3"), 2000);
observer.complete();

30/411
});

myObservable.subscribe(data => console.log(data));

Output:

scss

Value 1
Value 2
(Value 3 appears after 2 seconds)

What is the role of HttpClient in Angular? (Q52)


HttpClient is an Angular service used to make HTTP requests (GET, POST, PUT, DELETE). It is
provided by HttpClientModule .

🔹 Key Features:
Supports Observables for handling HTTP requests.

Handles automatic JSON parsing.

Supports interceptors for request/response modifications.

Steps for Fetching Data with HttpClient & Observable (Q53)

Step 1: Import HttpClientModule

In app.module.ts , import HttpClientModule :

typescript

import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [HttpClientModule]
})
export class AppModule { }

Step 2: Create an API Service

Create a service ( api.service.ts ) to handle HTTP requests.

31/411
typescript

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';

constructor(private http: HttpClient) {}

getPosts(): Observable<any> {
return this.http.get(this.apiUrl);
}
}

Step 3: Fetch Data in a Component

Inject the service and subscribe to the Observable.

typescript

import { Component, OnInit } from '@angular/core';


import { ApiService } from './api.service';

@Component({
selector: 'app-posts',
template: `<ul><li *ngFor="let post of posts">{{ post.title }}</li></ul>`
})
export class PostsComponent implements OnInit {
posts: any[] = [];

constructor(private apiService: ApiService) {}

ngOnInit() {
this.apiService.getPosts().subscribe(data => this.posts = data);
}
}

How to Handle HTTP Errors in Angular? (Q54)

32/411
To handle HTTP errors, use RxJS operators like catchError() .

Example: Handling Errors in the API Service

Modify getPosts() to handle errors.

typescript

import { catchError } from 'rxjs/operators';


import { throwError } from 'rxjs';

getPosts(): Observable<any> {
return this.http.get(this.apiUrl).pipe(
catchError(error => {
console.error("Error fetching data:", error);
return throwError(() => new Error("Something went wrong!"));
})
);
}

Example: Displaying Error Message in Component

typescript

ngOnInit() {
this.apiService.getPosts().subscribe({
next: data => this.posts = data,
error: err => console.error("Error:", err.message)
});
}

Summary
Concept Explanation

Promise vs Observable Promises return one value; Observables handle multiple values.

RxJS A reactive programming library used for handling async data streams.

Observable A stream that emits data over time (must be subscribed).

HttpClient Service used to make HTTP calls in Angular.

Fetching Data Use HttpClient with Observables ( subscribe() ).

Error Handling Use catchError() to manage API failures.

Would you like a real-world example using an API with pagination? 😊

33/411
Here’s a real-world example of fetching paginated API data using HttpClient , Observables , and
error handling in Angular.

Step 1: Install JSON Server (Mock API)


If you don’t have an API, you can use JSON Server to create a fake REST API.

1️⃣ Install JSON Server:


sh

npm install -g json-server

2️⃣ Create a file db.json with the following data:

json

{
"posts": [
{ "id": 1, "title": "Angular Basics", "content": "Learn Angular step by step" },
{ "id": 2, "title": "RxJS in Angular", "content": "Understanding Observables" },
{ "id": 3, "title": "HttpClient Usage", "content": "Making API calls in Angular" },
{ "id": 4, "title": "Pagination in Angular", "content": "Implementing load more
functionality" }
]
}

3️⃣ Start the server:


sh

json-server --watch db.json --port 3000

Now, the API is available at http://localhost:3000/posts .

Step 2: Import HttpClientModule in Angular


Modify app.module.ts to include HttpClientModule :

typescript

34/411
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Step 3: Create a Service to Fetch Paginated Data


Create post.service.ts inside src/app/services/ .

typescript

import { Injectable } from '@angular/core';


import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class PostService {
private apiUrl = 'http://localhost:3000/posts';

constructor(private http: HttpClient) {}

getPosts(page: number, limit: number): Observable<any> {


const url = `${this.apiUrl}?_page=${page}&_limit=${limit}`;
return this.http.get(url).pipe(
retry(2), // Retry failed requests twice
catchError(this.handleError) // Error handling
);
}

private handleError(error: HttpErrorResponse) {


console.error('Error fetching data:', error);
return throwError(() => new Error('Something went wrong. Please try again.'));

35/411
}
}

Step 4: Fetch Data in a Component


Modify app.component.ts to implement pagination with a Load More button.

typescript

import { Component, OnInit } from '@angular/core';


import { PostService } from './services/post.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2; // Load 2 posts per page
isLoading = false;
errorMessage = '';

constructor(private postService: PostService) {}

ngOnInit() {
this.loadPosts();
}

loadPosts() {
this.isLoading = true;
this.postService.getPosts(this.page, this.limit).subscribe({
next: (data) => {
this.posts = [...this.posts, ...data]; // Append new data
this.page++; // Increase page count
this.isLoading = false;
},
error: (error) => {
this.errorMessage = error.message;
this.isLoading = false;
}
});

36/411
}
}

Step 5: Display Data in the Template


Modify app.component.html to show posts and implement a Load More button.

html

<div class="container">
<h2>Blog Posts</h2>
<ul>
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
</li>
</ul>

<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>

<button (click)="loadPosts()" *ngIf="!isLoading">Load More</button>


<p *ngIf="isLoading">Loading...</p>
</div>

Step 6: Add Some CSS


Modify app.component.css for basic styling.

css

.container {
max-width: 600px;
margin: auto;
text-align: center;
}

ul {
list-style: none;
padding: 0;
}

37/411
li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}

button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
}

button:hover {
background: #0056b3;
}

.error {
color: red;
}

How It Works
✅ Initially, 2 posts are loaded.
✅ Clicking "Load More" fetches 2 more posts.
✅ If an error occurs, a message is displayed.
✅ If all posts are loaded, the button disappears.

Summary
Feature Implementation

API Setup Used JSON Server to simulate a REST API.

Service Created PostService to fetch paginated data.

Pagination Used _page and _limit parameters.

Retry & Error Handling Implemented retry(2) and catchError() .

Component Updates Appended new data using this.posts = [...this.posts, ...data];

38/411
Feature Implementation

Load More Functionality Increased page on each button click.

This is a real-world Angular project structure for handling API data, pagination, and error
management. 🚀
Would you like to add filtering or search functionality next? 🔍
Adding Filtering and Search Functionality in Angular
We will enhance our existing blog post list by adding:
✅ Search functionality (Filter posts by title)
✅ Category filtering (Filter posts based on categories)

Step 1: Modify the JSON Server Data


Update db.json with categories for each post:

json

{
"posts": [
{ "id": 1, "title": "Angular Basics", "content": "Learn Angular step by step",
"category": "Angular" },
{ "id": 2, "title": "RxJS in Angular", "content": "Understanding Observables",
"category": "RxJS" },
{ "id": 3, "title": "HttpClient Usage", "content": "Making API calls in Angular",
"category": "Angular" },
{ "id": 4, "title": "Pagination in Angular", "content": "Implementing load more
functionality", "category": "UI/UX" },
{ "id": 5, "title": "State Management in Angular", "content": "Using NgRx effectively",
"category": "NgRx" }
]
}

Restart the JSON Server:

sh

json-server --watch db.json --port 3000

39/411
Step 2: Update the Post Service
Modify post.service.ts to support search and category filtering.

typescript

import { Injectable } from '@angular/core';


import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class PostService {
private apiUrl = 'http://localhost:3000/posts';

constructor(private http: HttpClient) {}

// Fetch paginated posts with search & category filter


getPosts(page: number, limit: number, search: string = '', category: string = ''):
Observable<any> {
let url = `${this.apiUrl}?_page=${page}&_limit=${limit}`;

if (search) {
url += `&title_like=${search}`; // JSON Server supports "title_like" for filtering
}
if (category) {
url += `&category=${category}`;
}

return this.http.get(url).pipe(
retry(2),
catchError(this.handleError)
);
}

private handleError(error: HttpErrorResponse) {


console.error('Error fetching data:', error);
return throwError(() => new Error('Something went wrong. Please try again.'));
}
}

40/411
Step 3: Update the Component
Modify app.component.ts to handle search & category selection.

typescript

import { Component, OnInit } from '@angular/core';


import { PostService } from './services/post.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
isLoading = false;
errorMessage = '';
categories = ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx']; // Available categories

constructor(private postService: PostService) {}

ngOnInit() {
this.loadPosts();
}

loadPosts() {
this.isLoading = true;
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;

this.postService.getPosts(this.page, this.limit, this.searchText, category).subscribe({


next: (data) => {
this.posts = [...this.posts, ...data];
this.page++;
this.isLoading = false;
},
error: (error) => {
this.errorMessage = error.message;
this.isLoading = false;
}
});
}

41/411
onSearch() {
this.page = 1;
this.posts = [];
this.loadPosts();
}

onCategoryChange() {
this.page = 1;
this.posts = [];
this.loadPosts();
}
}

Step 4: Update the Template


Modify app.component.html to include:
✅ Search input
✅ Category dropdown
✅ Filtered results
html

<div class="container">
<h2>Blog Posts</h2>

<!-- Search Input -->


<input type="text" [(ngModel)]="searchText" placeholder="Search by title..."
(input)="onSearch()">

<!-- Category Dropdown -->


<select [(ngModel)]="selectedCategory" (change)="onCategoryChange()">
<option *ngFor="let cat of categories" [value]="cat">{{ cat }}</option>
</select>

<!-- Display Posts -->


<ul>
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>
</ul>

42/411
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>

<button (click)="loadPosts()" *ngIf="!isLoading">Load More</button>


<p *ngIf="isLoading">Loading...</p>
</div>

Step 5: Add Some Styling


Modify app.component.css for better UI.

css

.container {
max-width: 600px;
margin: auto;
text-align: center;
}

input, select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}

ul {
list-style: none;
padding: 0;
}

li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}

button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
cursor: pointer;

43/411
}

button:hover {
background: #0056b3;
}

.error {
color: red;
}

How It Works
✅ Search input: Filters posts as the user types.
✅ Category filter: Shows only posts from the selected category.
✅ Pagination: Click Load More to fetch more posts.
✅ Error handling: If something goes wrong, a message appears.

Summary
Feature Implementation

Search Uses title_like in API calls.

Category Filter Uses a dropdown with category in API calls.

Pagination Loads more posts on button click.

Optimized API Calls Resets list on search/category change.

Error Handling Shows error message on API failure.

🚀 Next Steps
Would you like to: 1️⃣ Add sorting (e.g., latest posts first)?
2️⃣ Implement infinite scrolling instead of a Load More button?
Enhancing Blog Post List with Sorting and Infinite Scroll

44/411
We'll now add:
✅ Sorting functionality (Sort posts by newest first)
✅ Infinite scrolling (Auto-load posts when the user scrolls)

Step 1: Modify the Service to Support Sorting


Update post.service.ts to include sorting by date.

typescript

getPosts(page: number, limit: number, search: string = '', category: string = '', sortBy:
string = 'id', order: string = 'desc'): Observable<any> {
let url = `${this.apiUrl}?_page=${page}&_limit=${limit}&_sort=${sortBy}&_order=${order}`;

if (search) {
url += `&title_like=${search}`;
}
if (category) {
url += `&category=${category}`;
}

return this.http.get(url).pipe(
retry(2),
catchError(this.handleError)
);
}

Step 2: Modify the Component to Support Sorting & Infinite


Scroll
Update app.component.ts :

typescript

import { Component, HostListener, OnInit } from '@angular/core';


import { PostService } from './services/post.service';

@Component({
selector: 'app-root',

45/411
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
selectedSort = 'id';
isLoading = false;
errorMessage = '';
categories = ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx'];
sortOptions = [{ label: 'Newest First', value: 'id' }, { label: 'Title (A-Z)', value:
'title' }];

constructor(private postService: PostService) {}

ngOnInit() {
this.loadPosts();
}

loadPosts() {
if (this.isLoading) return;

this.isLoading = true;
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;

this.postService.getPosts(this.page, this.limit, this.searchText, category,


this.selectedSort, 'desc').subscribe({
next: (data) => {
this.posts = [...this.posts, ...data];
this.page++;
this.isLoading = false;
},
error: (error) => {
this.errorMessage = error.message;
this.isLoading = false;
}
});
}

onSearch() {
this.resetPosts();
}

46/411
onCategoryChange() {
this.resetPosts();
}

onSortChange() {
this.resetPosts();
}

resetPosts() {
this.page = 1;
this.posts = [];
this.loadPosts();
}

@HostListener('window:scroll', [])
onScroll(): void {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
this.loadPosts();
}
}
}

Step 3: Modify the Template


Update app.component.html :

html

<div class="container">
<h2>Blog Posts</h2>

<input type="text" [(ngModel)]="searchText" placeholder="Search..." (input)="onSearch()">

<select [(ngModel)]="selectedCategory" (change)="onCategoryChange()">


<option *ngFor="let cat of categories" [value]="cat">{{ cat }}</option>
</select>

<select [(ngModel)]="selectedSort" (change)="onSortChange()">


<option *ngFor="let option of sortOptions" [value]="option.value">{{ option.label }}
</option>
</select>

<ul>

47/411
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>
</ul>

<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>


<p *ngIf="isLoading">Loading...</p>
</div>

How It Works
✅ Sorting: Select sort order from dropdown.
✅ Infinite Scrolling: Loads more posts when scrolling down.

🚀 Next Steps
Would you like to: 1️⃣ Add a "Back to Top" button?
2️⃣ Implement a skeleton loader for smooth UX?
Enhancing UX with "Back to Top" Button & Skeleton Loader
We'll now add:
✅ "Back to Top" button (Smoothly scrolls to the top)
✅ Skeleton Loader (Shows a placeholder while loading)

Step 1: Implement "Back to Top" Button


Modify app.component.ts :

typescript

import { Component, HostListener, OnInit } from '@angular/core';


import { PostService } from './services/post.service';

@Component({

48/411
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
selectedSort = 'id';
isLoading = false;
errorMessage = '';
categories = ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx'];
sortOptions = [{ label: 'Newest First', value: 'id' }, { label: 'Title (A-Z)', value:
'title' }];
showBackToTop = false; // Controls visibility of the button

constructor(private postService: PostService) {}

ngOnInit() {
this.loadPosts();
}

loadPosts() {
if (this.isLoading) return;

this.isLoading = true;
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;

this.postService.getPosts(this.page, this.limit, this.searchText, category,


this.selectedSort, 'desc').subscribe({
next: (data) => {
this.posts = [...this.posts, ...data];
this.page++;
this.isLoading = false;
},
error: (error) => {
this.errorMessage = error.message;
this.isLoading = false;
}
});
}

onSearch() {
this.resetPosts();

49/411
}

onCategoryChange() {
this.resetPosts();
}

onSortChange() {
this.resetPosts();
}

resetPosts() {
this.page = 1;
this.posts = [];
this.loadPosts();
}

@HostListener('window:scroll', [])
onScroll(): void {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
this.loadPosts();
}
this.showBackToTop = window.scrollY > 300;
}

scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}

Step 2: Implement Skeleton Loader


Modify app.component.html to show a loading placeholder:

html

<div class="container">
<h2>Blog Posts</h2>

<input type="text" [(ngModel)]="searchText" placeholder="Search..." (input)="onSearch()">

<select [(ngModel)]="selectedCategory" (change)="onCategoryChange()">


<option *ngFor="let cat of categories" [value]="cat">{{ cat }}</option>
</select>

50/411
<select [(ngModel)]="selectedSort" (change)="onSortChange()">
<option *ngFor="let option of sortOptions" [value]="option.value">{{ option.label }}
</option>
</select>

<ul>
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>

<!-- Skeleton Loader -->


<li *ngIf="isLoading">
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-text"></div>
</li>
</ul>

<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>

<!-- Back to Top Button -->


<button *ngIf="showBackToTop" class="back-to-top" (click)="scrollToTop()">⬆ Back to
Top</button>

<p *ngIf="isLoading">Loading...</p>
</div>

Step 3: Add Styling for Skeleton Loader & Back to Top


Modify app.component.css :

css

.container {
max-width: 600px;
margin: auto;
text-align: center;
}

input, select {
width: 100%;

51/411
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}

ul {
list-style: none;
padding: 0;
}

li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}

button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}

button:hover {
background: #0056b3;
}

/* Skeleton Loader */
.skeleton {
background: #ddd;
border-radius: 5px;
animation: shimmer 1.5s infinite;
}

.skeleton-title {
height: 20px;
width: 80%;
margin: 10px auto;
}

.skeleton-text {
height: 15px;
width: 90%;
margin: 5px auto;

52/411
}

@keyframes shimmer {
0% { background: #eee; }
50% { background: #ddd; }
100% { background: #eee; }
}

/* Back to Top Button */


.back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px;
background: #28a745;
}

.back-to-top:hover {
background: #218838;
}

How It Works
✅ Back to Top Button: Appears when scrolled 300px down.
✅ Smooth Scroll: Clicking the button smoothly scrolls to the top.
✅ Skeleton Loader: Shows placeholders while posts are loading.

🚀 Next Steps
Would you like to: 1️⃣ Add animations when new posts load?
2️⃣ Show a toast notification on error or success?
Enhancing UX with Animations & Toast Notifications
We'll now add:
✅ Fade-in animation for newly loaded posts
✅ Toast notifications for success & error messages

53/411
Step 1: Add Animations for Post Loading
Modify app.component.ts :

typescript

import { Component, HostListener, OnInit } from '@angular/core';


import { PostService } from './services/post.service';
import { trigger, transition, style, animate } from '@angular/animations';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [
trigger('fadeIn', [
transition(':enter', [
style({ opacity: 0, transform: 'translateY(10px)' }),
animate('500ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
])
])
]
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
selectedSort = 'id';
isLoading = false;
errorMessage = '';
showBackToTop = false;
showToast = false;
toastMessage = '';
toastType = 'success';

constructor(private postService: PostService) {}

ngOnInit() {
this.loadPosts();
}

loadPosts() {
if (this.isLoading) return;

this.isLoading = true;

54/411
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;

this.postService.getPosts(this.page, this.limit, this.searchText, category,


this.selectedSort, 'desc').subscribe({
next: (data) => {
this.posts = [...this.posts, ...data];
this.page++;
this.isLoading = false;
this.showToastMessage('Posts loaded successfully!', 'success');
},
error: (error) => {
this.errorMessage = error.message;
this.isLoading = false;
this.showToastMessage('Error loading posts', 'error');
}
});
}

onSearch() {
this.resetPosts();
}

onCategoryChange() {
this.resetPosts();
}

onSortChange() {
this.resetPosts();
}

resetPosts() {
this.page = 1;
this.posts = [];
this.loadPosts();
}

@HostListener('window:scroll', [])
onScroll(): void {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
this.loadPosts();
}
this.showBackToTop = window.scrollY > 300;
}

scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });

55/411
}

showToastMessage(message: string, type: 'success' | 'error') {


this.toastMessage = message;
this.toastType = type;
this.showToast = true;

setTimeout(() => {
this.showToast = false;
}, 3000);
}
}

Step 2: Modify HTML for Animations & Toast Notifications


Update app.component.html :

html

<div class="container">
<h2>Blog Posts</h2>

<input type="text" [(ngModel)]="searchText" placeholder="Search..." (input)="onSearch()">

<select [(ngModel)]="selectedCategory" (change)="onCategoryChange()">


<option *ngFor="let cat of ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx']" [value]="cat">{{
cat }}</option>
</select>

<select [(ngModel)]="selectedSort" (change)="onSortChange()">


<option *ngFor="let option of [{ label: 'Newest First', value: 'id' }, { label: 'Title (A-
Z)', value: 'title' }]" [value]="option.value">{{ option.label }}</option>
</select>

<ul>
<li *ngFor="let post of posts" @fadeIn>
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>

<!-- Skeleton Loader -->


<li *ngIf="isLoading">

56/411
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-text"></div>
</li>
</ul>

<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>

<!-- Toast Notification -->


<div *ngIf="showToast" class="toast" [ngClass]="toastType">
{{ toastMessage }}
</div>

<!-- Back to Top Button -->


<button *ngIf="showBackToTop" class="back-to-top" (click)="scrollToTop()">⬆ Back to
Top</button>

<p *ngIf="isLoading">Loading...</p>
</div>

Step 3: Add Styles for Animations & Toast Notifications


Modify app.component.css :

css

.container {
max-width: 600px;
margin: auto;
text-align: center;
}

input, select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}

ul {
list-style: none;
padding: 0;
}

57/411
li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}

/* Skeleton Loader */
.skeleton {
background: #ddd;
border-radius: 5px;
animation: shimmer 1.5s infinite;
}

.skeleton-title {
height: 20px;
width: 80%;
margin: 10px auto;
}

.skeleton-text {
height: 15px;
width: 90%;
margin: 5px auto;
}

@keyframes shimmer {
0% { background: #eee; }
50% { background: #ddd; }
100% { background: #eee; }
}

/* Back to Top Button */


.back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px;
background: #28a745;
border-radius: 5px;
color: white;
}

.back-to-top:hover {
background: #218838;
}

58/411
/* Toast Notification */
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
color: white;
border-radius: 5px;
font-weight: bold;
animation: fadeInOut 3s ease-in-out;
}

.toast.success {
background: #28a745;
}

.toast.error {
background: #dc3545;
}

@keyframes fadeInOut {
0% { opacity: 0; transform: translateY(10px); }
20% { opacity: 1; transform: translateY(0); }
80% { opacity: 1; }
100% { opacity: 0; transform: translateY(-10px); }
}

How It Works
✅ Fade-in Animation: Posts smoothly appear when loaded.
✅ Toast Notifications: Shows a success or error message for 3 seconds.

🚀 Next Steps
Would you like to:
1️⃣ Add a dark mode toggle?
2️⃣ Enhance the toast notifications with icons?

59/411
What is the difference between let and var keyword ?
03:03
Q58. What is Type annotation ?
01:28
Q59.What are Built in/Primitive & UserDefined/Non-primitive types
in Typescript?
01:53
Q61. What is Enum type in Typescript ?
02:11
Q62. What is the difference between void and never types in
Typescript ?
01:32
Q63. What is Type Assertion in Typescript ?
01:57
Q64. What are Arrow Functions in Typescript ?

Here are the answers to your TypeScript-related questions:

Q57: What is the difference between let and var keyword?

var (Function-scoped)

Declared variables are function-scoped (accessible throughout the function).

Can be re-declared in the same scope.

Variables are hoisted but initialized as undefined .

let (Block-scoped)

Declared variables are block-scoped (limited to {} block).

Cannot be re-declared in the same scope.

Variables are hoisted but not initialized (throws an error if accessed before declaration).

Example:

typescript

function testVarLet() {
if (true) {
var a = 10; // Function-scoped
let b = 20; // Block-scoped
}
console.log(a); // ✅ Works (because `var` is function-scoped)
console.log(b); // ❌ Error (because `let` is block-scoped)

60/411
}
testVarLet();

Q58: What is Type Annotation?


Type annotation in TypeScript is used to explicitly define the type of a variable, function, or parameter.

Example:

typescript

let age: number = 30;


let name: string = "John";
function greet(name: string): string {
return "Hello, " + name;
}

Here, number and string are type annotations.

Q59: What are Built-in (Primitive) & User-Defined (Non-Primitive) Types in


TypeScript?

Primitive (Built-in) Types

These are basic types:

string

number

boolean

null

undefined

bigint

symbol

Example:

typescript

61/411
let isDone: boolean = true;
let score: number = 95;
let message: string = "Hello!";

Non-Primitive (User-Defined) Types

These include:

arrays

objects

tuples

enums

functions

classes

interfaces

Example:

typescript

let colors: string[] = ["red", "blue"];


let person: { name: string; age: number } = { name: "Alice", age: 25 };

Q61: What is enum type in TypeScript?


Enums allow defining a set of named constants.

Example (Numeric Enum):

typescript

enum Status {
Pending, // 0
InProgress, // 1
Completed // 2
}
console.log(Status.InProgress); // Output: 1

Example (String Enum):

typescript

62/411
enum Direction {
Up = "UP",
Down = "DOWN"
}
console.log(Direction.Up); // Output: "UP"

Q62: What is the difference between void and never types in TypeScript?
Feature void never

Usage Used when a function does not Used for functions that never return (throw
return a value error or infinite loop)

Return Value Can return undefined Never returns anything

Example

```typescript

function logMessage():
void {

console.log("Logging...");

| ```typescript
function throwError(): never {
throw new Error("This will never return");
}
``` |

---

### **Q63: What is Type Assertion in TypeScript?**


Type assertion allows manually specifying a variable's type.

##### **Example (`as` syntax):**


```typescript
let someValue: unknown = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;
console.log(strLength); // Output: 17

Example ( <> syntax - not used in JSX):

63/411
typescript

let someValue: unknown = "Hello";


let strLength: number = (<string>someValue).length;

Q64: What are Arrow Functions in TypeScript?


Arrow functions are shorthand for writing functions using => syntax.

Example:

typescript

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


console.log(add(5, 3)); // Output: 8

Key Features:

✅ Concise syntax
✅ No binding (uses parent scope’s
this this )

Example of this behavior in Arrow Function:

typescript

class Person {
name = "Alice";
sayHello = () => {
console.log("Hello, " + this.name);
};
}
const p = new Person();
p.sayHello(); // Output: Hello, Alice

Let me know if you need further clarification! 🚀


What is Object-oriented programming in Typescript-explain in
detail

Object-Oriented Programming (OOP) in TypeScript - Detailed Explanation


TypeScript fully supports Object-Oriented Programming (OOP) concepts, making it a powerful
language for building scalable and maintainable applications.

64/411
OOP Concepts in TypeScript
1. Classes and Objects

2. Encapsulation

3. Inheritance

4. Polymorphism

5. Abstraction

1. Classes and Objects in TypeScript


What is a Class?
A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that
objects will have.

What is an Object?
An object is an instance of a class. It contains values for the properties defined in the class.

Example:
typescript

class Person {
name: string;
age: number;

constructor(name: string, age: number) {


this.name = name;
this.age = age;
}

greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

// Creating an object

65/411
let person1 = new Person("John", 30);
person1.greet(); // Output: Hello, my name is John and I am 30 years old.

2. Encapsulation
Encapsulation is the process of restricting direct access to class properties and methods to protect
data.

Access Modifiers in TypeScript


Modifier Description

public Accessible anywhere (default).

private Accessible only within the class.

protected Accessible within the class and subclasses.

Example of Encapsulation:

typescript

class BankAccount {
private balance: number = 0;

deposit(amount: number): void {


if (amount > 0) {
this.balance += amount;
console.log(`Deposited: ${amount}, New Balance: ${this.balance}`);
}
}

getBalance(): number {
return this.balance;
}
}

let myAccount = new BankAccount();


myAccount.deposit(1000);
console.log(myAccount.getBalance()); // Output: 1000
// myAccount.balance = 5000; ❌ Error: balance is private

66/411
3. Inheritance
Inheritance allows a class to inherit properties and methods from another class, promoting code
reusability.

Example of Inheritance:

typescript

class Animal {
constructor(public name: string) {}

makeSound(): void {
console.log("Some sound...");
}
}

class Dog extends Animal {


bark(): void {
console.log(`${this.name} is barking!`);
}
}

let myDog = new Dog("Buddy");


myDog.makeSound(); // Output: Some sound...
myDog.bark(); // Output: Buddy is barking!

Here, Dog inherits from Animal , gaining access to makeSound() .

4. Polymorphism
Polymorphism allows a subclass to override a method of its superclass, providing different
implementations.

Example of Polymorphism:

typescript

class Shape {
area(): void {
console.log("Calculating area...");
}
}

67/411
class Circle extends Shape {
radius: number;

constructor(radius: number) {
super();
this.radius = radius;
}

area(): void {
console.log(`Circle Area: ${Math.PI * this.radius * this.radius}`);
}
}

let myCircle = new Circle(5);


myCircle.area(); // Output: Circle Area: 78.54

Here, the Circle class overrides the area() method.

5. Abstraction
Abstraction hides implementation details and only exposes necessary functionalities.

Abstract Classes in TypeScript


An abstract class cannot be instantiated directly. It contains abstract methods that must be
implemented by derived classes.

Example of Abstraction:

typescript

abstract class Vehicle {


abstract move(): void;

start(): void {
console.log("Vehicle is starting...");
}
}

class Car extends Vehicle {


move(): void {
console.log("Car is moving...");
}

68/411
}

let myCar = new Car();


myCar.start(); // Output: Vehicle is starting...
myCar.move(); // Output: Car is moving...

Here, move() is an abstract method that must be implemented in subclasses.

Conclusion
TypeScript’s Object-Oriented Programming (OOP) features enhance code organization, reusability,
and maintainability. The key OOP principles include:

✅ Classes & Objects - Define blueprints and create instances


✅ Encapsulation - Protects data with access modifiers
✅ Inheritance - Promotes code reuse
✅ Polymorphism - Enables method overriding
✅ Abstraction - Hides details and enforces implementation
Would you like an example with interfaces as well? 🚀

What are Classes and Objects in Typescript ?


02:05
Q67. What is Constructor ?
02:18
Q68. What are Access Modifiers in Typescript ?
04:01
Q69. What is Encapsulation in Typescript?
05:50
Q70. What is Inheritance in Typescript ?
02:50
Q71. What is Polymorphism in Typescript ?
02:46
Q72. What is Interface in Typescript ?
04:34
Q73. What's the difference between extends and implements in
TypeScript?
01:28
Q74. Is Multiple Inheritance possible in Typescript ?

Q66: What are Classes and Objects in TypeScript?

Classes:

69/411
A class is a blueprint for creating objects.

It defines properties (variables) and methods (functions) that objects will have.

Objects:

An object is an instance of a class.

It contains values for the properties defined in the class.

Example:

typescript

class Person {
name: string;
age: number;

constructor(name: string, age: number) {


this.name = name;
this.age = age;
}

greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

// Creating an object (instance)


let person1 = new Person("John", 30);
person1.greet(); // Output: Hello, my name is John and I am 30 years old.

Q67: What is a Constructor in TypeScript?


A constructor is a special method inside a class that initializes an object’s properties.

It is automatically called when an object is created.

Example:

typescript

class Car {
model: string;

constructor(model: string) {

70/411
this.model = model;
}

showModel(): void {
console.log(`Car Model: ${this.model}`);
}
}

let myCar = new Car("Tesla Model S");


myCar.showModel(); // Output: Car Model: Tesla Model S

Q68: What are Access Modifiers in TypeScript?


Access Modifiers control the visibility of class properties and methods.

Modifier Description

public Accessible anywhere (default).

private Accessible only within the class.

protected Accessible within the class and its subclasses.

Example:

typescript

class BankAccount {
private balance: number;

constructor(balance: number) {
this.balance = balance;
}

getBalance(): number {
return this.balance; // ✅ Allowed
}
}

let account = new BankAccount(1000);


console.log(account.getBalance()); // ✅ Allowed
// console.log(account.balance); ❌ Error: Property 'balance' is private.

71/411
Q69: What is Encapsulation in TypeScript?
Encapsulation is the concept of hiding data and allowing controlled access using methods.

Achieved using private or protected properties.

Improves data security and maintainability.

Example:

typescript

class Employee {
private salary: number;

constructor(salary: number) {
this.salary = salary;
}

getSalary(): number {
return this.salary; // Controlled access
}
}

let emp = new Employee(5000);


console.log(emp.getSalary()); // ✅ Allowed
// console.log(emp.salary); ❌ Error: Property 'salary' is private.

Q70: What is Inheritance in TypeScript?


Inheritance allows a class (child class) to inherit properties and methods from another class (parent
class).

Example:

typescript

class Animal {
name: string;

constructor(name: string) {
this.name = name;
}

makeSound(): void {

72/411
console.log("Some sound...");
}
}

class Dog extends Animal {


bark(): void {
console.log(`${this.name} is barking!`);
}
}

let myDog = new Dog("Buddy");


myDog.makeSound(); // Output: Some sound...
myDog.bark(); // Output: Buddy is barking!

Here, Dog inherits from Animal , gaining access to makeSound() .

Q71: What is Polymorphism in TypeScript?


Polymorphism allows a subclass to override a method from its superclass, providing different
implementations.

Example:

typescript

class Shape {
area(): void {
console.log("Calculating area...");
}
}

class Circle extends Shape {


radius: number;

constructor(radius: number) {
super();
this.radius = radius;
}

area(): void { // Overriding parent method


console.log(`Circle Area: ${Math.PI * this.radius * this.radius}`);
}
}

73/411
let myCircle = new Circle(5);
myCircle.area(); // Output: Circle Area: 78.54

Q72: What is an Interface in TypeScript?


An interface is a structure that defines the shape of an object, ensuring that it follows a specific
contract.

Used for defining properties and methods but does not contain implementation.

Can be implemented in classes.

Example:

typescript

interface IAnimal {
name: string;
makeSound(): void;
}

class Dog implements IAnimal {


name: string;

constructor(name: string) {
this.name = name;
}

makeSound(): void {
console.log(`${this.name} says Woof!`);
}
}

let myDog = new Dog("Charlie");


myDog.makeSound(); // Output: Charlie says Woof!

Q73: What’s the difference between extends and implements in TypeScript?


Feature extends implements

Used for Inheritance between classes Implementing interfaces in classes

74/411
Feature extends implements

Number of Parent(s) Single parent class Multiple interfaces allowed

Can contain method implementation? Yes No (only defines structure)

Example ( extends - Class Inheritance):

typescript

class Parent {
greet(): void {
console.log("Hello from Parent class!");
}
}

class Child extends Parent {


sayHi(): void {
console.log("Hi from Child class!");
}
}

let obj = new Child();


obj.greet(); // ✅ Allowed (inherited from Parent)
obj.sayHi(); // ✅ Allowed

Example ( implements - Interface Implementation):

typescript

interface Printable {
print(): void;
}

class Document implements Printable {


print(): void {
console.log("Printing document...");
}
}

let doc = new Document();


doc.print(); // ✅ Allowed

Q74: Is Multiple Inheritance possible in TypeScript?

75/411
No, TypeScript does not support multiple inheritance (i.e., a class cannot extend multiple classes).

Example ( ❌ Invalid Multiple Inheritance):


typescript

class A {}
class B {}
class C extends A, B {} // ❌ Error: Multiple inheritance is not allowed
Solution: Use Interfaces for Multiple Inheritance

While multiple inheritance is not allowed, you can implement multiple interfaces.

Example ( ✅ Implementing Multiple Interfaces):


typescript

interface Flyable {
fly(): void;
}

interface Swimmable {
swim(): void;
}

class Bird implements Flyable, Swimmable {


fly(): void {
console.log("Bird is flying!");
}

swim(): void {
console.log("Bird is swimming!");
}
}

let myBird = new Bird();


myBird.fly(); // Output: Bird is flying!
myBird.swim(); // Output: Bird is swimming!

Conclusion
✅ Classes & Objects - Define blueprints and create instances
✅ Constructor - Initializes an object’s properties

76/411
✅ Access Modifiers - public , private, protected
✅ Encapsulation - Hides data and allows controlled access
✅ Inheritance - Allows code reuse between classes
✅ Polymorphism - Enables method overriding
✅ Interfaces - Define contracts for classes
✅ Extends vs Implements - Inheritance vs interface implementation
✅ Multiple Inheritance - Not supported, but multiple interfaces can be implemented
Would you like further clarifications or examples? 🚀

How to setup Template Driven Forms ?


03:49
Q78. How to apply Required field validation in template driven
forms?
03:18
Q79. What is Form Group and Form Control in Angular ?
05:05
Q80. How to setup Reactive Forms ?
05:10
Q81. How to do validations in reactive forms ?

Template-Driven Forms and Reactive Forms in Angular

Q77: How to set up Template-Driven Forms in Angular?


Template-driven forms rely on directives in the HTML template and are simpler for basic use cases.

Steps to set up Template-Driven Forms:

1️⃣ Import FormsModule in app.module.ts :

typescript

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule], // Import FormsModule
bootstrap: [AppComponent]
})
export class AppModule {}

2️⃣ Create the form in HTML ( app.component.html )

77/411
html

<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">


<label for="name">Name:</label>
<input type="text" id="name" name="name" ngModel required>

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

Here, ngModel binds the input to a model variable.

3️⃣ Handle form submission in Component ( app.component.ts )

typescript

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
onSubmit(form: any) {
console.log("Form Submitted:", form.value);
}
}

✅ Now, the form is ready, and values will be logged when submitted.

Q78: How to apply Required Field Validation in Template-Driven Forms?


Use the required attribute and #formControl="ngModel" for error handling.

html

<form #userForm="ngForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel required #emailField="ngModel">

<div *ngIf="emailField.invalid && emailField.touched">


<p>Email is required.</p>
</div>

78/411
<button [disabled]="userForm.invalid">Submit</button>
</form>

🔹 The form is invalid unless a valid email is entered.


🔹 The error message appears when the field is touched but empty.

Q79: What is FormGroup and FormControl in Angular?


Reactive Forms use FormGroup and FormControl to manage form states in the component.

FormControl : Represents a single form input field.

FormGroup : A collection of FormControl s (like a full form).

Example:

typescript

import { Component } from '@angular/core';


import { FormGroup, FormControl } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});

onSubmit() {
console.log(this.userForm.value);
}
}

Q80: How to set up Reactive Forms?


1️⃣ Import ReactiveFormsModule in app.module.ts :

typescript

79/411
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [ReactiveFormsModule]
})
export class AppModule {}

2️⃣ Create a FormGroup in Component ( app.component.ts )

typescript

import { Component } from '@angular/core';


import { FormGroup, FormControl } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});

onSubmit() {
console.log(this.userForm.value);
}
}

3️⃣ Bind it to the HTML ( app.component.html )

html

<form [formGroup]="userForm" (ngSubmit)="onSubmit()">


<label for="name">Name:</label>
<input id="name" formControlName="name">

<label for="email">Email:</label>
<input id="email" formControlName="email">

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

✅ Now, the form is bound to userForm and submits data via the component.

80/411
Q81: How to do Validations in Reactive Forms?
Use Angular’s Validators to add validation rules.

1️⃣ Import Validators


typescript

import { FormGroup, FormControl, Validators } from '@angular/forms';

2️⃣ Add Validators in the FormGroup


typescript

userForm = new FormGroup({


name: new FormControl('', [Validators.required, Validators.minLength(3)]),
email: new FormControl('', [Validators.required, Validators.email])
});

3️⃣ Display Validation Messages in HTML


html

<form [formGroup]="userForm" (ngSubmit)="onSubmit()">


<label>Name:</label>
<input formControlName="name">
<div *ngIf="userForm.get('name')?.invalid && userForm.get('name')?.touched">
<p *ngIf="userForm.get('name')?.errors?.required">Name is required.</p>
<p *ngIf="userForm.get('name')?.errors?.minlength">Minimum 3 characters required.</p>
</div>

<label>Email:</label>
<input formControlName="email">
<div *ngIf="userForm.get('email')?.invalid && userForm.get('email')?.touched">
<p *ngIf="userForm.get('email')?.errors?.required">Email is required.</p>
<p *ngIf="userForm.get('email')?.errors?.email">Invalid email format.</p>
</div>

<button [disabled]="userForm.invalid">Submit</button>
</form>

✅ Now, the form is validated dynamically.


It shows error messages when fields are invalid.

The Submit button is disabled if the form is invalid.

81/411
Comparison: Template-Driven vs. Reactive Forms
Feature Template-Driven Forms Reactive Forms

Setup Uses FormsModule Uses ReactiveFormsModule

Form Handling Handled in HTML Managed in the Component

Form Control Uses ngModel Uses FormControl

Validation Uses HTML attributes (e.g., required ) Uses Validators in TypeScript

Use Case Simple forms Complex forms (dynamic forms, custom validators)

Summary
✅ Template-Driven Forms - Uses , simpler, HTML-driven.
ngModel
✅ Reactive Forms - Uses FormGroup , FormControl , and for better control.
Validators
✅ Validations - Apply required fields and validation messages using Angular’s built-in features.
Would you like more examples or explanations? 🚀

Explain Authentication & Authorization in Angular with real-world


examples.

Authentication & Authorization in Angular


Authentication and Authorization are crucial security mechanisms in any Angular application that
interacts with a backend. Let’s break them down with real-world examples.

1️⃣ Authentication in Angular


🔹 Authentication verifies a user's identity.
🔹 Users log in with a username/password (or OAuth, etc.), and the system authenticates them by
checking credentials.
🔹 On success, the system issues a JWT (JSON Web Token) or a session token.
Example: Login Authentication in Angular (Using JWT)

Backend (Node.js/Java, etc.) returns a JWT token on successful login.

82/411
🔹 Step 1: Create an Authentication Service ( auth.service.ts )

This service will handle login, logout, and token storage.

typescript

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class AuthService {
private baseUrl = 'https://your-api-url.com/auth'; // Backend API URL

constructor(private http: HttpClient) {}

// Login API Call


login(credentials: { email: string; password: string }): Observable<any> {
return this.http.post(`${this.baseUrl}/login`, credentials);
}

// Store JWT Token


storeToken(token: string) {
localStorage.setItem('token', token);
}

// Retrieve Token
getToken(): string | null {
return localStorage.getItem('token');
}

// Logout
logout() {
localStorage.removeItem('token');
}

// Check if user is authenticated


isAuthenticated(): boolean {
return !!localStorage.getItem('token');
}
}

83/411
🔹 Step 2: Implement Login Component ( login.component.ts )

typescript

import { Component } from '@angular/core';


import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
email = '';
password = '';

constructor(private authService: AuthService, private router: Router) {}

login() {
this.authService.login({ email: this.email, password: this.password }).subscribe(
(response) => {
this.authService.storeToken(response.token); // Store token in local storage
this.router.navigate(['/dashboard']); // Redirect to dashboard
},
(error) => {
console.error('Login failed:', error);
}
);
}
}

🔹 Step 3: Create Login Form ( login.component.html )

html

<form (ngSubmit)="login()">
<label>Email:</label>
<input type="email" [(ngModel)]="email" name="email" required />

<label>Password:</label>
<input type="password" [(ngModel)]="password" name="password" required />

84/411
<button type="submit">Login</button>
</form>

🔹 Step 4: Protect Routes Using Auth Guard ( auth.guard.ts )

AuthGuard prevents unauthenticated users from accessing certain routes.

typescript

import { Injectable } from '@angular/core';


import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']); // Redirect to login if not authenticated
return false;
}
}
}

🔹 Step 5: Apply Auth Guard to Secure Routes ( app-routing.module.ts )

typescript

import { NgModule } from '@angular/core';


import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './services/auth.guard';

const routes: Routes = [

85/411
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, // Protected
Route
{ path: 'login', component: LoginComponent }, // Public Route
{ path: '', redirectTo: '/login', pathMatch: 'full' } // Default Route
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}

✅ Now, only authenticated users can access the /dashboard route.

2️⃣ Authorization in Angular


🔹 Authorization determines what a user can do based on roles/permissions.
🔹 Example:
An admin can access all pages.

A user can only access limited sections.

🔹 Step 6: Implement Role-Based Authorization


Modify AuthService to include user roles.

typescript

storeUserRole(role: string) {
localStorage.setItem('userRole', role);
}

getUserRole(): string | null {


return localStorage.getItem('userRole');
}

86/411
🔹 Step 7: Create a Role-Based Guard ( role.guard.ts )

typescript

import { Injectable } from '@angular/core';


import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(): boolean {
const role = this.authService.getUserRole();
if (role === 'admin') {
return true;
} else {
this.router.navigate(['/access-denied']); // Redirect unauthorized users
return false;
}
}
}

🔹 Step 8: Apply Role Guard to Admin Routes


typescript

const routes: Routes = [


{ path: 'admin', component: AdminComponent, canActivate: [RoleGuard] }, // Only for Admins
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full' }
];

✅ Now, only Admins can access /admin route.

3️⃣ Real-World Example


87/411
Imagine an Online Banking System:

Authentication:

Users must log in with their credentials before accessing their bank accounts.

Authorization:

Regular users can only view account details & transfer money.

Bank staff can approve transactions.

Admins can manage users and monitor transactions.

4️⃣ Summary
🔹 Authentication → Verifies who the user is (Login System).
🔹 Authorization → Controls what the user can do (Role-Based Access).
🔹 Angular Guards → Protect routes using authentication and roles.
🔹 JWT Token → Used to store login sessions securely.
🚀 Would you like help with backend integration for JWT?
JWT Authentication with Angular and Java Spring Boot Backend
Now, let’s integrate JWT authentication with a Java Spring Boot backend to handle user authentication.

1️⃣ Backend: Spring Boot JWT Authentication


The backend will:
✔ Authenticate users
✔ Generate JWT tokens
✔ Verify token validity

🔹 Step 1: Add Dependencies (Spring Boot)


In pom.xml , add:

xml

88/411
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

🔹 Step 2: Create User Model


java

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;

89/411
// Getters & Setters
}

🔹 Step 3: Create User Repository


java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}

🔹 Step 4: Create JWT Utility


java

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class JwtUtil {
private String secretKey = "your_secret_key"; // Change this for production

public String generateToken(String username) {


return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // 1
hour expiry
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
}

public String extractUsername(String token) {


return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()

90/411
.getSubject();
}

public boolean validateToken(String token, String username) {


return username.equals(extractUsername(token)) && !isTokenExpired(token);
}

private boolean isTokenExpired(String token) {


return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()
.getExpiration()
.before(new Date());
}
}

🔹 Step 5: Create Authentication Service


java

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;

@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;

public AuthService(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtUtil


jwtUtil) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.jwtUtil = jwtUtil;
}

public String login(String username, String password) {


Optional<User> userOptional = userRepository.findByUsername(username);
if (userOptional.isPresent() && passwordEncoder.matches(password,
userOptional.get().getPassword())) {
return jwtUtil.generateToken(username);

91/411
}
throw new RuntimeException("Invalid username or password");
}

public void register(User user) {


user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
}

🔹 Step 6: Create Authentication Controller


java

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;

public AuthController(AuthService authService) {


this.authService = authService;
}

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
String token = authService.login(request.getUsername(), request.getPassword());
return ResponseEntity.ok(new AuthResponse(token));
}

@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody User user) {
authService.register(user);
return ResponseEntity.ok("User registered successfully");
}
}

92/411
🔹 Step 7: Create Security Configuration
java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

protected void configure(HttpSecurity http) throws Exception {


http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
}
}

🔹 Step 8: Test Login API


Run the backend and use Postman or Angular frontend to test:
✅ POST http://localhost:8080/auth/login
✅ POST http://localhost:8080/auth/register

2️⃣ Angular Frontend Integration


Now, let’s integrate this backend with your Angular frontend.

🔹 Step 1: Install HttpClientModule

93/411
typescript

import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [HttpClientModule]
})
export class AppModule { }

🔹 Step 2: Modify Auth Service ( auth.service.ts )

typescript

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'http://localhost:8080/auth';

constructor(private http: HttpClient) {}

login(credentials: { username: string; password: string }): Observable<any> {


return this.http.post(`${this.apiUrl}/login`, credentials);
}

register(user: { username: string; password: string }): Observable<any> {


return this.http.post(`${this.apiUrl}/register`, user);
}

storeToken(token: string) {
localStorage.setItem('token', token);
}

getToken(): string | null {


return localStorage.getItem('token');
}

logout() {
localStorage.removeItem('token');

94/411
}
}

🔹 Step 3: Modify Login Component ( login.component.ts )

typescript

import { Component } from '@angular/core';


import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
username = '';
password = '';

constructor(private authService: AuthService, private router: Router) {}

login() {
this.authService.login({ username: this.username, password: this.password }).subscribe(
(response) => {
this.authService.storeToken(response.token);
this.router.navigate(['/dashboard']);
},
(error) => {
console.error('Login failed:', error);
}
);
}
}

✅ Summary
1. Spring Boot Backend

Implements JWT authentication.

95/411
Secures endpoints with Spring Security.

2. Angular Frontend

Stores the JWT token.

Uses AuthService for login/logout.

🚀 Next Steps? Want role-based access control?


What is JWT Token Authentication in Angular ?
02:50
Q84. How to Mock or Fake an API for JWT Authentication ?
04:14
Q85. How to implement the Authentication with JWT in Angular ?
09:42
Q86. What is Auth Guard ?
05:18
Q87. What is HTTP Interceptor ?
08:37
Q88. How to Retry automatically if there is an error response from
API ?
01:53
Q89. What are the parts of JWT Token ?
01:55
Q90. What is Postman ?
01:44
Q91. Which part of the request has the token stored when sending
to API ?

JWT Authentication in Angular


JWT (JSON Web Token) is a secure way to implement authentication in Angular by storing and
verifying tokens.

Q84: How to Mock or Fake an API for JWT Authentication?


You can mock an API for JWT authentication using json-server or Mock Service Worker (MSW).

🔹 Using json-server
1. Install json-server

sh

npm install -g json-server

96/411
2. Create db.json

json

{
"users": [
{ "id": 1, "username": "admin", "password": "12345", "token": "mock-jwt-token" }
]
}

3. Run the fake API


sh

json-server --watch db.json --port 3000

4. Now, http://localhost:3000/users acts as a mock API.

Q85: How to Implement JWT Authentication in Angular?

1️⃣ Install @auth0/angular-jwt

sh

npm install @auth0/angular-jwt

2️⃣ Configure Authentication Service ( auth.service.ts )

typescript

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'http://localhost:3000';

constructor(private http: HttpClient) {}

login(credentials: { username: string; password: string }): Observable<any> {


return this.http.post(`${this.apiUrl}/users`, credentials);
}

97/411
storeToken(token: string) {
localStorage.setItem('token', token);
}

getToken(): string | null {


return localStorage.getItem('token');
}

logout() {
localStorage.removeItem('token');
}
}

Q86: What is an Auth Guard?


Auth Guard protects routes based on authentication status.

🔹 Create auth.guard.ts

typescript

import { Injectable } from '@angular/core';


import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(): boolean {
if (this.authService.getToken()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}

🔹 Protect Routes in app-routing.module.ts

98/411
typescript

const routes: Routes = [


{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];

Q87: What is HTTP Interceptor?


Interceptors modify outgoing HTTP requests to include JWT tokens.

🔹 Create auth.interceptor.ts

typescript

import { Injectable } from '@angular/core';


import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('token');
if (token) {
req = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next.handle(req);
}
}

🔹 Register in app.module.ts

typescript

import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
})
export class AppModule { }

99/411
Q88: How to Retry Automatically on API Error?
Use retry() from RxJS.

typescript

import { catchError, retry } from 'rxjs/operators';


import { throwError } from 'rxjs';

this.http.get('api/data')
.pipe(
retry(3),
catchError(error => throwError(() => error))
)
.subscribe();

Q89: Parts of a JWT Token


A JWT consists of:

1. Header → Metadata about the token

2. Payload → User data (username, roles)

3. Signature → Verifies token authenticity

Example JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.dGVzdFNpZ25hdHVyZQ

Q90: What is Postman?


Postman is an API testing tool used to:

Send HTTP requests (GET, POST, PUT, DELETE)

Add headers, authentication, and test responses

100/411
Q91: Where is the JWT Token Stored in a Request?
✅ Stored in the Authorization Header
http

Authorization: Bearer <JWT_TOKEN>

✅ Summary
✔ Mock API using json-server
✔ Implement JWT authentication in Angular
✔ Use Auth Guards to protect routes
✔ Use Interceptors to attach tokens
✔ Retry API calls on failure

🚀 Want role-based authentication? Let me know!

What is Content Projection? What is <ng-content>?


05:28
Q94. What is Template Reference Variable in Angular ?
02:07
Q95. What is the role of View Child in Angular?
05:30
Q96. How to access the child component from parent component
with View Child?
03:00
Q97. Difference between ViewChild and ViewChildren? What is
QueryList ?
05:04
Q98. What is ContentChild ?
06:00
Q99. What is the difference between ContentChild &
ContentChildren ?
02:45
Q100.Compare ng-Content,ViewChild, ViewChildren, ContentChild
& ContentChildren?

Content Projection, ViewChild, ViewChildren, ContentChild & ContentChildren


in Angular

101/411
Q93: What is Content Projection? What is <ng-content> ?
✅ Content Projection allows inserting external HTML into a component dynamically.
✅ <ng-content>acts as a placeholder for projected content.

Example:

📌 Parent Component ( app.component.html )

html

<app-card>
<h2>Title from Parent</h2>
<p>Content from Parent</p>
</app-card>

📌 Child Component ( card.component.html )

html

<div class="card">
<ng-content></ng-content>
</div>

📌 Output
html

<div class="card">
<h2>Title from Parent</h2>
<p>Content from Parent</p>
</div>

Q94: What is Template Reference Variable in Angular?


✅ #varName allows direct access to an element or a directive inside a template.

Example:

html

<input #myInput type="text" />


<button (click)="logValue(myInput.value)">Log Input</button>

typescript

102/411
logValue(value: string) {
console.log(value);
}

Q95: What is the Role of ViewChild in Angular?


✅ @ViewChild gives access to child component, directive, or DOM elements from the parent.

Example: Accessing Child Component

📌 Child Component ( child.component.ts )

typescript

import { Component } from '@angular/core';


@Component({
selector: 'app-child',
template: `<h2>Child Component</h2>`
})
export class ChildComponent {
message = "Hello from Child!";
}

📌 Parent Component ( parent.component.ts )

typescript

import { Component, ViewChild, AfterViewInit } from '@angular/core';


import { ChildComponent } from './child.component';

@Component({
selector: 'app-parent',
template: `<app-child></app-child> <button (click)="showMessage()">Get Child
Message</button>`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child!: ChildComponent;

ngAfterViewInit() {
console.log(this.child.message);
}

showMessage() {
alert(this.child.message);

103/411
}
}

Q96: How to Access Child Component from Parent using ViewChild?


✅ Use @ViewChild(ChildComponent) in Parent Component.
✅ Use ngAfterViewInit() to ensure child is initialized.

(See Q95 example for implementation.)

Q97: Difference between ViewChild and ViewChildren? What is QueryList?


Feature ViewChild ViewChildren

Returns Single instance Multiple instances

Type Component, directive, or DOM element List of elements

Return Type Child component instance QueryList<T>

Example @ViewChild(ChildComponent) @ViewChildren(ChildComponent)

Example: ViewChildren with QueryList

typescript

import { ViewChildren, QueryList, AfterViewInit } from '@angular/core';

@ViewChildren(ChildComponent) children!: QueryList<ChildComponent>;

ngAfterViewInit() {
this.children.forEach(child => console.log(child.message));
}

Q98: What is ContentChild?


✅ @ContentChild retrieves a projected single element inside <ng-content> .

Example:

📌 Parent Component ( app.component.html )

104/411
html

<app-container>
<h2 #title>Projected Title</h2>
</app-container>

📌 Child Component ( container.component.ts )

typescript

import { ContentChild, ElementRef, AfterContentInit } from '@angular/core';

@ContentChild('title') title!: ElementRef;

ngAfterContentInit() {
console.log(this.title.nativeElement.innerText);
}

Q99: Difference between ContentChild & ContentChildren?


Feature ContentChild ContentChildren

Returns Single element Multiple elements

Works with @ContentChild('templateRef') @ContentChildren('templateRef')

Used with ng-content elements Multiple projected elements

Q100: Comparison of <ng-content> , ViewChild , ViewChildren , ContentChild


& ContentChildren
<ng-
Feature content> ViewChild ViewChildren ContentChild ContentChildren

Purpose Project Access single child Access Access single Access multiple
external component multiple child projected element projected
content components elements

Use Dynamic DOM manipulation Looping Fetching one Fetching multiple


Case content through projected element projected
children elements

105/411
<ng-
Feature content> ViewChild ViewChildren ContentChild ContentChildren

Return N/A Component/Element QueryList<T> Component/Element QueryList<T>


Type

✅ Summary
✔ Content Projection → <ng-content>
✔ ViewChild → Access child component or DOM element
✔ ViewChildren → Access multiple child components
✔ ContentChild → Access single projected content
✔ ContentChildren → Access multiple projected contents

🚀 Need an example with advanced use cases? Let me know!


Here's an advanced example demonstrating the use of <ng-content> , ViewChild , ViewChildren ,
ContentChild , and ContentChildren together in an Angular project.

🛠 Advanced Example - Using ViewChild, ViewChildren,


ContentChild & ContentChildren
Step 1: Create a Child Component ( child.component.ts )
This component will be used inside a parent component and also projected inside <ng-content> .

typescript

import { Component, Input } from '@angular/core';

@Component({
selector: 'app-child',
template: `<p>Child Component - Message: {{ message }}</p>`,
styles: [`p { color: blue; font-weight: bold; }`]
})
export class ChildComponent {
@Input() message: string = 'Default Message';
}

106/411
Step 2: Create a Parent Component ( parent.component.ts )
Uses @ViewChild to access a single child component.

Uses @ViewChildren to access multiple child components.

Uses @ContentChild to access a single projected element.

Uses @ContentChildren to access multiple projected elements.

typescript

import {
Component, ViewChild, ViewChildren, ContentChild, ContentChildren, QueryList, ElementRef,
AfterViewInit
} from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
selector: 'app-parent',
template: `
<h2>Parent Component</h2>

<!-- ViewChild Example: Single Child Component -->


<app-child #singleChild message="Hello from ViewChild!"></app-child>

<!-- ViewChildren Example: Multiple Child Components -->


<app-child message="Child 1"></app-child>
<app-child message="Child 2"></app-child>
<app-child message="Child 3"></app-child>

<!-- Content Projection Example -->


<app-container>
<p #projectedContent>Projected Content inside ng-content</p>
<app-child message="Projected Child 1"></app-child>
<app-child message="Projected Child 2"></app-child>
</app-container>

<button (click)="showDetails()">Show Details</button>


`
})
export class ParentComponent implements AfterViewInit {
// ViewChild - Access single child component
@ViewChild('singleChild') singleChild!: ChildComponent;

// ViewChildren - Access multiple child components


@ViewChildren(ChildComponent) multipleChildren!: QueryList<ChildComponent>;

107/411
// ContentChild - Access single projected content
@ContentChild('projectedContent') projectedElement!: ElementRef;

// ContentChildren - Access multiple projected elements


@ContentChildren(ChildComponent) projectedChildren!: QueryList<ChildComponent>;

ngAfterViewInit() {
console.log('ViewChild Message:', this.singleChild.message);
console.log('ViewChildren Messages:', this.multipleChildren.map(child => child.message));
}

showDetails() {
console.log('Projected Content:', this.projectedElement.nativeElement.innerText);
console.log('Projected Children Messages:', this.projectedChildren.map(child =>
child.message));
}
}

Step 3: Create a Container Component ( container.component.ts )


This will handle Content Projection with <ng-content> .

typescript

import { Component, ContentChild, ContentChildren, QueryList, ElementRef, AfterContentInit }


from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
selector: 'app-container',
template: `
<div class="container">
<h3>Container Component</h3>
<ng-content></ng-content>
</div>
`,
styles: [`.container { border: 1px solid black; padding: 10px; margin-top: 10px; }`]
})
export class ContainerComponent implements AfterContentInit {
// ContentChild - Access projected single element
@ContentChild('projectedContent') projectedElement!: ElementRef;

// ContentChildren - Access projected multiple child components

108/411
@ContentChildren(ChildComponent) projectedChildren!: QueryList<ChildComponent>;

ngAfterContentInit() {
console.log('ContentChild (Projected Content):',
this.projectedElement.nativeElement.innerText);
console.log('ContentChildren (Projected Child Components):',
this.projectedChildren.map(child => child.message));
}
}

🎯 Expected Output
1. ViewChild: Access single child component.

2. ViewChildren: Access all instances of ChildComponent inside ParentComponent .

3. ContentChild: Access one projected element inside <ng-content> .

4. ContentChildren: Access all projected ChildComponent instances.

📌 Summary
Feature Access Scope Use Case Example

ViewChild Single child Access one child component @ViewChild('singleChild')


or DOM element

ViewChildren Multiple children Access multiple child @ViewChildren(ChildComponent)


components

ContentChild Single projected Access a single element @ContentChild('projectedContent')


element inside <ng-content>

ContentChildren Multiple Access all projected elements @ContentChildren(ChildComponent)


projected inside <ng-content>
elements

🚀 Now, your Angular project efficiently uses Content Projection & Component Queries!
Would you like more details or modifications? 😊

What are some important string operations in JS?


02:10
Q5. What is DOM? What is the difference between HTML and

109/411
DOM?
02:31
Q6. What are selectors in JS?
01:05
Q7. Difference getElementById, getElementsByClassName and get
elementsByTagName?
02:42
Q8. What are data types in JS?

Important String Operations in JavaScript


1. String Length

js

let str = "Hello, World!";


console.log(str.length); // 13

2. Accessing Characters

js

console.log(str[0]); // 'H'
console.log(str.charAt(1)); // 'e'

3. Substring Extraction

slice(start, end)

substring(start, end)

substr(start, length)

js

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


console.log(str.substring(0, 5)); // 'Hello'
console.log(str.substr(7, 5)); // 'World'

4. String Search

indexOf()

lastIndexOf()

includes()

js

console.log(str.indexOf("World")); // 7
console.log(str.lastIndexOf("o")); // 8

110/411
console.log(str.includes("Hello")); // true

5. String Replacement

replace()

replaceAll()

js

console.log(str.replace("Hello", "Hi")); // 'Hi, World!'


console.log(str.replaceAll("o", "0")); // 'Hell0, W0rld!'

6. String Conversion

toUpperCase()

toLowerCase()

js

console.log(str.toUpperCase()); // 'HELLO, WORLD!'


console.log(str.toLowerCase()); // 'hello, world!'

7. String Concatenation

concat()

js

console.log(str.concat(" How are you?")); // 'Hello, World! How are you?'

8. Trimming Strings

trim()

trimStart()

trimEnd()

js

let text = " Hello World! ";


console.log(text.trim()); // 'Hello World!'

9. Splitting Strings

split()

js

111/411
console.log(str.split(",")); // ['Hello', ' World!']

What is DOM? Difference between HTML and DOM


DOM (Document Object Model) represents the HTML structure as a hierarchical tree that JavaScript
can manipulate dynamically.

Feature HTML DOM

Definition Markup language defining webpage structure Programming interface for web documents

Static/Dynamic Static Dynamic

Used for Structuring content Manipulating content

Selectors in JavaScript
Selectors are methods to find elements in the DOM.

1. ID Selector – document.getElementById("id")

2. Class Selector – document.getElementsByClassName("class")

3. Tag Selector – document.getElementsByTagName("tag")

4. Query Selector – document.querySelector(".class")

5. Query Selector All – document.querySelectorAll(".class")

Difference Between getElementById , getElementsByClassName , and


getElementsByTagName

Access
Method Returns Type Example

getElementById("id") Single element Direct document.getElementById("myId")


object
reference

getElementsByClassName("class") HTMLCollection Live document.getElementsByClassName("myClass")


(multiple collection
elements)

112/411
Access
Method Returns Type Example

getElementsByTagName("tag") HTMLCollection Live document.getElementsByTagName("div")


(multiple collection
elements)

Data Types in JavaScript


1. Primitive Types

String

Number

Boolean

BigInt

Symbol

Undefined

Null

js

let name = "John"; // String


let age = 25; // Number
let isLoggedIn = true; // Boolean
let bigNum = BigInt(9007199254740991); // BigInt
let id = Symbol('id'); // Symbol
let x; // Undefined
let y = null; // Null

2. Non-Primitive Types (Reference Types)

Object

Array

Function

js

let person = { name: "Alice", age: 30 }; // Object


let numbers = [1, 2, 3, 4, 5]; // Array
function greet() { console.log("Hello"); } // Function

113/411
Would you like examples on any specific topic? 🚀
What are operators in JS and their different types?

Operators in JavaScript and Their Types


Operators in JavaScript are symbols that perform operations on values and variables.

1. Arithmetic Operators
These operators are used for mathematical calculations.

Operator Description Example

+ Addition 5 + 2 // 7

- Subtraction 5 - 2 // 3

* Multiplication 5 * 2 // 10

/ Division 5 / 2 // 2.5

% Modulus (Remainder) 5 % 2 // 1

++ Increment let a = 5; a++; // 6

-- Decrement let a = 5; a--; // 4

2. Assignment Operators
These operators assign values to variables.

Operator Description Example

= Assigns value x = 10

+= Adds and assigns x += 5 // x = x + 5

-= Subtracts and assigns x -= 5 // x = x - 5

*= Multiplies and assigns x *= 5 // x = x * 5

/= Divides and assigns x /= 5 // x = x / 5

%= Modulus and assigns x %= 5 // x = x % 5

114/411
3. Comparison Operators
These operators compare values and return true or false .

Operator Description Example

== Equal to (value only) 5 == "5" // true

=== Strict equal (value + type) 5 === "5" // false

!= Not equal to (value only) 5 != "5" // false

!== Strict not equal (value + type) 5 !== "5" // true

> Greater than 10 > 5 // true

< Less than 10 < 5 // false

>= Greater than or equal 10 >= 5 // true

<= Less than or equal 10 <= 5 // false

4. Logical Operators
Used to combine multiple conditions.

Operator Description Example

&& Logical AND (5 > 2 && 10 > 5) // true

` `

! Logical NOT !(5 > 2) // false

5. Bitwise Operators
These operators work on binary numbers.

Operator Description Example

& AND 5 & 1 // 1

` ` OR

^ XOR 5 ^ 1 // 4

~ NOT ~5 // -6

<< Left Shift 5 << 1 // 10

>> Right Shift 5 >> 1 // 2

115/411
6. Ternary Operator
A shortcut for if-else conditions.

js

let result = (5 > 2) ? "Yes" : "No";


console.log(result); // "Yes"

7. Type Operators
Used to determine data types.

Operator Description Example

typeof Returns the data type typeof "Hello" // "string"

instanceof Checks if an object is an instance of a class arr instanceof Array // true

8. Nullish Coalescing Operator ( ?? )


Returns the right-hand value if the left-hand value is null or undefined .

js

let name = null;


console.log(name ?? "Guest"); // "Guest"

Would you like more details or examples on any specific operator? 🚀


What are the types of conditions statements in JS?
03:19
Q11. What is a loop? What are the types of loops in JS?
01:25
Q12. What are Functions in JS? What are the types of function?
01:26
Q13. What are Arrow Functions in JS? What is it use?

116/411
02:14
Q14. What are Arrays in JS? How to get, add & remove elements
from arrays?
02:59
Q15. What are Objects in JS?
02:00
Q16. What is Scope in JavaScript?
01:24
Q17. What is Hoisting in JavaScript?
01:49
Q18. What is Error Handling in JS?
01:16
Q19. What is JSON?
01:00
Q20. What is asynchronous programming in JS? What is its use?

Answers to JavaScript Concepts

Q10. What are the types of conditional statements in JavaScript?

Conditional statements are used to execute different blocks of code based on conditions.

1. if Statement

js

let age = 18;


if (age >= 18) {
console.log("You are an adult.");
}

2. if-else Statement

js

let num = 10;


if (num > 0) {
console.log("Positive number");
} else {
console.log("Negative number or zero");
}

3. else-if Ladder

js

let marks = 75;


if (marks >= 90) {

117/411
console.log("A Grade");
} else if (marks >= 75) {
console.log("B Grade");
} else {
console.log("C Grade");
}

4. Ternary Operator

js

let isMember = true;


let discount = isMember ? "10% Discount" : "No Discount";
console.log(discount);

5. Switch Case

js

let day = "Monday";


switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Weekend is coming");
break;
default:
console.log("Normal day");
}

Q11. What is a loop? What are the types of loops in JavaScript?

A loop is used to execute a block of code multiple times.

Types of Loops:

1. for Loop

js

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


console.log(i);
}

118/411
2. while Loop

js

let i = 1;
while (i <= 5) {
console.log(i);
i++;
}

3. do-while Loop

js

let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);

4. forEach (Array Loop)

js

let arr = [1, 2, 3];


arr.forEach(num => console.log(num));

Q12. What are Functions in JavaScript? What are the types of functions?

A function is a reusable block of code that performs a specific task.

Types of Functions:

1. Named Function

js

function greet() {
return "Hello!";
}
console.log(greet());

2. Anonymous Function

js

119/411
let greet = function() {
return "Hello!";
};
console.log(greet());

3. Arrow Function

js

let greet = () => "Hello!";


console.log(greet());

4. Immediately Invoked Function Expression (IIFE)

js

(function() {
console.log("I am an IIFE!");
})();

Q13. What are Arrow Functions in JavaScript? What is its use?

Arrow functions provide a shorter syntax for writing functions and do not bind their own this .

js

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


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

Uses:

Shorter syntax

No need for function keyword

No this binding (useful in callbacks)

Q14. What are Arrays in JavaScript? How to get, add & remove elements from arrays?

An array is a collection of multiple values in a single variable.

js

120/411
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Access an element

Adding Elements:

js

fruits.push("Orange"); // Adds at end


fruits.unshift("Grapes"); // Adds at beginning

Removing Elements:

js

fruits.pop(); // Removes last element


fruits.shift(); // Removes first element
fruits.splice(1, 1); // Removes specific index

Q15. What are Objects in JavaScript?

Objects store key-value pairs.

js

let person = {
name: "John",
age: 25,
greet: function() {
return "Hello!";
}
};
console.log(person.name); // John
console.log(person.greet()); // Hello!

Q16. What is Scope in JavaScript?

Scope determines where a variable can be accessed.

1. Global Scope - Available everywhere

js

121/411
let globalVar = "I am global";

2. Function Scope - Available inside a function

js

function test() {
let localVar = "I am local";
}

3. Block Scope (let, const) - Available inside {}

js

if (true) {
let blockVar = "I am block-scoped";
}

Q17. What is Hoisting in JavaScript?

Hoisting moves function and variable declarations to the top of their scope.

js

console.log(x); // Undefined (due to hoisting)


var x = 5;

Functions are fully hoisted:

js

greet(); // Works!
function greet() {
console.log("Hello!");
}

Q18. What is Error Handling in JavaScript?

Error handling prevents crashes using try...catch .

js

122/411
try {
let x = undefinedVariable; // Throws error
} catch (error) {
console.log("Error caught:", error.message);
} finally {
console.log("This runs always.");
}

Q19. What is JSON?

JSON (JavaScript Object Notation) is a lightweight data format.

js

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


let obj = JSON.parse(jsonString); // Convert JSON to object
console.log(obj.name); // Alice

let newJson = JSON.stringify(obj); // Convert object to JSON


console.log(newJson);

Q20. What is Asynchronous Programming in JavaScript? What is its use?

Asynchronous programming allows JavaScript to execute code without blocking.

Example (setTimeout - Asynchronous Execution):

js

console.log("Start");
setTimeout(() => console.log("Async Task"), 2000);
console.log("End");

Uses:

Improves performance

Handles API requests

Supports real-time applications

123/411
Let me know if you need more details on any topic! 🚀
What are variables? What is the difference between var, let, and
const ?
03:32
Q22. What are data types in JS?
01:23
Q23. What is the difference between primitive and non-primitive
data types?
04:07
Q24. What is the difference between null and undefined in JS?
02:22
Q25. What is the use of typeof operator?
01:16
Q26. What is type coercion in JS?

JavaScript Variables & Data Types

Q21. What are variables? What is the difference between var , let , and const ?

A variable is used to store values in JavaScript.

js

var x = 10;
let y = 20;
const z = 30;

Differences:

Feature var let const

Scope Function-scoped Block-scoped Block-scoped

Re-declaration Allowed Not allowed Not allowed

Re-assignment Allowed Allowed Not allowed

Hoisting Hoisted with undefined Hoisted without value Hoisted without value

Example:

js

console.log(a); // Undefined (due to hoisting)


var a = 5;

// console.log(b); // ReferenceError: Cannot access 'b' before initialization


let b = 10;

124/411
Q22. What are data types in JavaScript?

JavaScript has two categories of data types:

1. Primitive Data Types

String → "Hello"

Number → 42

Boolean → true , false

Null → null

Undefined → undefined

Symbol → Symbol('id')

BigInt → 9007199254740991n

2. Non-Primitive (Reference) Data Types

Object

Array

Function

Q23. What is the difference between primitive and non-primitive data types?

Feature Primitive Data Type Non-Primitive Data Type

Stored in Stack Heap

Copied by Value Reference

Mutability Immutable Mutable

Example:

js

let x = 5; // Primitive (stores value)


let y = x;
y = 10;
console.log(x); // 5 (remains unchanged)

let obj1 = { name: "Alice" }; // Non-Primitive (stores reference)


let obj2 = obj1;

125/411
obj2.name = "Bob";
console.log(obj1.name); // "Bob" (changes because of reference)

Q24. What is the difference between null and undefined in JavaScript?

Feature null undefined

Type Object Undefined

Meaning Empty or intentional absence of value Variable declared but not assigned

Use case Explicitly assigned Default value for uninitialized variables

Example:

js

let a;
console.log(a); // undefined

let b = null;
console.log(b); // null

Q25. What is the use of the typeof operator?

The typeof operator returns the data type of a variable.

js

console.log(typeof "Hello"); // "string"


console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (a known JavaScript bug)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"

Q26. What is type coercion in JavaScript?

126/411
Type coercion automatically converts values between types.

Implicit Coercion (Automatic conversion)

js

console.log("5" + 3); // "53" (string)


console.log("5" - 3); // 2 (number)
console.log("5" * "2"); // 10 (number)
console.log(5 + true); // 6 (true = 1)
console.log(5 + false); // 5 (false = 0)

Explicit Coercion (Manual conversion)

js

console.log(Number("42")); // 42
console.log(String(42)); // "42"
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true

Let me know if you need more details! 🚀


What are operators? What are the types of operators in JS?
03:46
Q28. What is the difference between unary, binary, and ternary
operators?
01:33
Q29. What is short-circuit evaluation in JS?
02:16
Q30. What is operator precedence?
00:54
Q31. What are the types of conditions statements in JS?
03:19
Q32. When to use which type of conditions statements in real
applications?
03:32
Q33. What is the difference between == and ===?
01:46
Q34. What is the difference between Spread and Rest operator in
JS?

JavaScript Operators

127/411
Q27. What are operators? What are the types of operators in JavaScript?

Operators are symbols that perform operations on variables or values.

🔹 Types of Operators in JavaScript


1. Arithmetic Operators ( + , - , * , / , % , ** )

js

console.log(5 + 3); // 8
console.log(10 % 3); // 1 (remainder)
console.log(2 ** 3); // 8 (exponentiation)

2. Comparison Operators ( == , === , != , !== , > , < , >= , <= )

js

console.log(5 == "5"); // true (loose comparison)


console.log(5 === "5"); // false (strict comparison)

3. Logical Operators ( && , || , ! )

js

console.log(true && false); // false


console.log(true || false); // true
console.log(!true); // false

4. Assignment Operators ( = , += , -= , *= , /= , %= , **= )

js

let x = 10;
x += 5; // x = x + 5
console.log(x); // 15

5. Bitwise Operators ( & , | , ^ , ~ , << , >> , >>> )

js

console.log(5 & 1); // 1 (bitwise AND)


console.log(5 | 1); // 5 (bitwise OR)

6. Ternary Operator ( condition ? expr1 : expr2 )

js

let age = 20;


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

128/411
console.log(status); // "Adult"

7. Type Operators ( typeof , instanceof )

js

console.log(typeof "Hello"); // "string"


console.log([] instanceof Array); // true

8. Spread and Rest Operators ( ... )

Spread: Expands elements

Rest: Collects elements

Q28. What is the difference between unary, binary, and ternary operators?

Operator Type Description Example

Unary Operates on one operand x = -5 ( - is unary)

Binary Operates on two operands x + y ( + is binary)

Ternary Operates on three operands condition ? expr1 : expr2

🔹 Examples:
js

// Unary
let a = 10;
console.log(-a); // -10

// Binary
let b = 5 + 3;
console.log(b); // 8

// Ternary
let age = 18;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message); // "Adult"

Q29. What is short-circuit evaluation in JavaScript?

129/411
Short-circuiting means stopping evaluation once the result is determined.

🔹 Logical AND ( && ) → Stops if the first operand is false

js

console.log(false && "Hello"); // false (stops early)


console.log(true && "Hello"); // "Hello"

🔹 Logical OR ( || ) → Stops if the first operand is true

js

console.log(true || "Hello"); // true (stops early)


console.log(false || "Hello"); // "Hello"

Q30. What is operator precedence?

Operator precedence determines the order in which expressions are evaluated.

🔹 Order (High to Low):


1. () – Parentheses

2. ** – Exponentiation

3. * , / , % – Multiplication, Division, Modulus

4. + , - – Addition, Subtraction

5. <, >, <=, >= – Comparison

6. ==, !=, ===, !== – Equality

7. && – Logical AND

8. || – Logical OR

9. =, +=, -= – Assignment

🔹 Example:
js

console.log(2 + 3 * 4); // 14 (Multiplication first)


console.log((2 + 3) * 4); // 20 (Parentheses first)

130/411
Conditional Statements in JavaScript

Q31. What are the types of conditional statements in JavaScript?

1. if Statement

js

let num = 10;


if (num > 5) {
console.log("Greater than 5");
}

2. if-else Statement

js

let age = 18;


if (age >= 18) {
console.log("Eligible to vote");
} else {
console.log("Not eligible");
}

3. if-else if-else Statement

js

let score = 85;


if (score >= 90) {
console.log("Grade A");
} else if (score >= 80) {
console.log("Grade B");
} else {
console.log("Grade C");
}

4. Switch Statement

js

let day = "Monday";


switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Weekend is near!");

131/411
break;
default:
console.log("Regular day");
}

Q32. When to use which type of conditional statements in real applications?

Condition Type When to Use

if Simple conditions

if-else Two possible outcomes

if-else if Multiple conditions

switch When checking multiple fixed values

🔹 Example Use Case:


js

// Using if-else for user authentication


let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome!");
} else {
console.log("Please log in.");
}

// Using switch for role-based access


let role = "admin";
switch (role) {
case "admin":
console.log("Full access");
break;
case "editor":
console.log("Limited access");
break;
default:
console.log("No access");
}

Q33. What is the difference between == and === ?

132/411
Operator Type Example Result

== Loose equality "5" == 5 true (Type conversion happens)

=== Strict equality "5" === 5 false (No type conversion)

🔹 Example:
js

console.log("5" == 5); // true (type coercion)


console.log("5" === 5); // false (strict comparison)

Q34. What is the difference between Spread and Rest operators in JavaScript?

Both use ... , but they serve different purposes.

🔹 Spread Operator ( ... ) → Expands elements

js

let arr = [1, 2, 3];


let newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]

🔹 Rest Operator ( ... ) → Collects elements

js

function sum(...nums) {
return nums.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3, 4)); // 10

That covers operators and conditionals in JavaScript! 🚀


Let me know if you need more explanations! 😊
What are Arrays in JS? How to get, add & remove elements from
arrays?
02:59
Q36. What is the indexOf() method of an Array?
00:48

133/411
Q37. What is the difference between find() and filter() methods of
an Array?
03:02
Q38. What is the slice() method of an Array?
01:16
Q39. What is the difference between push() and concat () methods
of an Array ?
01:27
Q40. What is the difference between pop() and shift() methods of
an Array?
01:22
Q41. What is the splice() method of an Array?
03:27
Q42. Difference between the slice() and splice() methods of an
Array?
00:40
Q43. What is the difference map() and for Each() array methods of
an Array?
02:37
Q44. How to sort and reverse an array?
00:51
Q45. What is Array Destructuring in JS?
01:38
Q46. What are array-like objects In JS?
02:52
Q47. How to convert an array-like object into an array?

JavaScript Arrays – Getting, Adding & Removing Elements


Q35. What are Arrays in JS? How to get, add & remove elements from arrays?
An array in JavaScript is a special variable that can hold multiple values in a single variable.

🔹 Creating an Array
js

let fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits); // ["Apple", "Banana", "Cherry"]

Getting Elements from an Array


Using index (Starts from 0)

js

134/411
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
console.log(fruits[fruits.length - 1]); // "Cherry"

Using forEach()

js

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

Adding Elements to an Array


At the End ( push() )

js

fruits.push("Mango");
console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"]

At the Beginning ( unshift() )

js

fruits.unshift("Grapes");
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry", "Mango"]

Removing Elements from an Array


From the End ( pop() )

js

fruits.pop();
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry"]

From the Beginning ( shift() )

js

135/411
fruits.shift();
console.log(fruits); // ["Apple", "Banana", "Cherry"]

Array Methods & Differences


Q36. What is the indexOf() method of an Array?
Returns the first index of an element in an array, or -1 if not found.

js

let numbers = [10, 20, 30, 40, 20];


console.log(numbers.indexOf(20)); // 1 (First occurrence)
console.log(numbers.indexOf(50)); // -1 (Not found)

Q37. Difference between find() and filter() methods


Method Returns Example

find() First matching element arr.find(el => el > 10);

filter() All matching elements arr.filter(el => el > 10);

js

let numbers = [5, 10, 15, 20, 25];

console.log(numbers.find(num => num > 10)); // 15 (First match)


console.log(numbers.filter(num => num > 10)); // [15, 20, 25] (All matches)

Q38. What is the slice() method of an Array?


Returns a new sub-array without modifying the original array.

js

136/411
let arr = ["A", "B", "C", "D", "E"];
console.log(arr.slice(1, 4)); // ["B", "C", "D"]
console.log(arr); // ["A", "B", "C", "D", "E"] (Original unchanged)

Q39. Difference between push() and concat() methods


Method Purpose Modifies Original?

push() Adds elements to an array ✅ Yes


concat() Merges arrays ❌ No
js

let arr1 = [1, 2, 3];


let arr2 = [4, 5];

arr1.push(6);
console.log(arr1); // [1, 2, 3, 6]

let newArr = arr1.concat(arr2);


console.log(newArr); // [1, 2, 3, 6, 4, 5]
console.log(arr1); // [1, 2, 3, 6] (Original unchanged)

Q40. Difference between pop() and shift() methods


Method Removes from Returns Removed Item Modifies Original?

pop() End ✅ Yes ✅ Yes


shift() Beginning ✅ Yes ✅ Yes
js

let items = ["Pen", "Book", "Eraser"];

console.log(items.pop()); // "Eraser"
console.log(items.shift()); // "Pen"
console.log(items); // ["Book"]

137/411
Q41. What is the splice() method of an Array?
Modifies an array by adding/removing elements.

js

let numbers = [10, 20, 30, 40];

// Remove 2 elements starting from index 1


numbers.splice(1, 2);
console.log(numbers); // [10, 40]

// Add elements at index 1


numbers.splice(1, 0, 25, 35);
console.log(numbers); // [10, 25, 35, 40]

Q42. Difference between slice() and splice()


Method Returns Modifies Original?

slice() New sub-array ❌ No


splice() Removed elements ✅ Yes
js

let arr = ["A", "B", "C", "D"];

console.log(arr.slice(1, 3)); // ["B", "C"] (Original unchanged)


console.log(arr.splice(1, 2)); // ["B", "C"] (Original modified)
console.log(arr); // ["A", "D"]

Q43. Difference between map() and forEach()


Method Returns New Array? Purpose

map() ✅ Yes Transforms elements

forEach() ❌ No Iterates over elements

js

138/411
let nums = [1, 2, 3];

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


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

nums.forEach(num => console.log(num * 2)); // Prints: 2, 4, 6

Q44. How to sort and reverse an array?


Sort ( sort() )

js

let fruits = ["Banana", "Apple", "Mango"];


fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango"]

Reverse ( reverse() )

js

fruits.reverse();
console.log(fruits); // ["Mango", "Banana", "Apple"]

Q45. What is Array Destructuring in JS?


Extracting values from an array into variables.

js

let colors = ["Red", "Green", "Blue"];


let [first, second, third] = colors;
console.log(first, second, third); // "Red Green Blue"

Q46. What are array-like objects in JS?

139/411
Objects that look like arrays but lack array methods.

Example: arguments object in functions.

js

function showArgs() {
console.log(arguments[0]); // "Hello"
}
showArgs("Hello", "World");

Q47. How to convert an array-like object into an array?


Using Array.from()

js

function convertToArray() {
let arr = Array.from(arguments);
console.log(arr);
}
convertToArray(1, 2, 3); // [1, 2, 3]

🚀 That’s a complete overview of JavaScript Arrays & Methods! Let me know if you need more details!
😊
What is a loop? What are the types of loops in JS?
01:25
Q49. What is the difference between while and for loops?
02:13
Q50. What is the difference between while and do-while loops?
01:50
Q51. What is the difference between break and continue
statement?
01:35
Q52. What is the difference between for and for…of loop in JS?
01:32
Q53. What is the difference between for…of and for…in loop?
01:28
Q54. What is forEach method? Compare it with for…of and for…in

140/411
loop?
02:32
Q55. When to use for…of loop and when to use forEach method in
applications?

JavaScript Loops – Types & Differences


Q48. What is a loop? What are the types of loops in JS?
A loop is a programming structure that repeats a block of code multiple times.

Types of Loops in JavaScript:


1. for loop – Iterates a fixed number of times.

2. while loop – Repeats while a condition is true.

3. do...while loop – Executes at least once, then repeats while a condition is true.

4. for...in loop – Iterates over object properties.

5. for...of loop – Iterates over iterable objects like arrays, strings, etc.

Q49. Difference between while and for loops?


Feature for Loop while Loop

Use Case When the number of iterations is known When the number of iterations is unknown

Structure for(init; condition; increment) while(condition)

Example for(let i=0; i<5; i++) while(i<5)

Example:

js

// for loop
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}

// while loop
let j = 0;
while (j < 3) {
console.log(j);
j++;
}

141/411
Q50. Difference between while and do...while loops?
Feature while Loop do...while Loop

Execution Condition First checks condition, then executes Executes at least once, then checks condition

Guaranteed Execution? No Yes (at least once)

Example:

js

// while loop (won't run if condition is false initially)


let a = 5;
while (a < 5) {
console.log("Inside while"); // Doesn't execute
}

// do...while loop (executes at least once)


let b = 5;
do {
console.log("Inside do...while"); // Executes once
} while (b < 5);

Q51. Difference between break and continue statements?


Feature break continue

Use Case Stops the loop completely Skips the current iteration, continues next

Effect on Loop Exits loop early Skips to the next iteration

Example:

js

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


if (i === 3) break;
console.log(i); // 0, 1, 2 (stops at 3)
}

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


if (i === 3) continue;

142/411
console.log(i); // 0, 1, 2, 4 (skips 3)
}

Q52. Difference between for and for...of loops in JS?


Feature for Loop for...of Loop

Use Works with index-based iteration (arrays, Iterates directly over values of iterables (arrays,
Case loops) strings)

Syntax for (let i = 0; i < arr.length; i++) for (let value of arr)

Example:

js

let numbers = [10, 20, 30];

// Using for loop


for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]); // 10, 20, 30
}

// Using for...of loop


for (let num of numbers) {
console.log(num); // 10, 20, 30
}

Q53. Difference between for...of and for...in loops?


Feature for...of for...in

Use Iterates over values of an iterable (arrays, Iterates over keys (property names) of an
Case strings) object

Best For Arrays, strings, iterables Objects

Returns Values Keys

Example:

js

143/411
let arr = ["Apple", "Banana", "Cherry"];
for (let fruit of arr) {
console.log(fruit); // "Apple", "Banana", "Cherry"
}

let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key, obj[key]); // "a 1", "b 2", "c 3"
}

Q54. What is forEach() method? Compare with for...of and for...in .


Feature forEach() for...of for...in

Use Case Iterates over arrays Iterates over iterable values Iterates over object keys

Returns No return, just executes Values Keys

Modifies Array? No (callback function needed) No No

Example:

js

let arr = [1, 2, 3];

// forEach()
arr.forEach(num => console.log(num * 2)); // 2, 4, 6

// for...of
for (let num of arr) {
console.log(num * 2); // 2, 4, 6
}

Q55. When to use for...of and when to use forEach() ?


Feature for...of forEach()

Best Use Case When needing break or continue When applying a function to each element

Syntax Works with break / continue Cannot break loop early

Performance Slightly faster Slightly slower due to callback overhead

144/411
Use for...of when:

You need to break or continue the loop.

You are iterating over iterables like arrays and strings.

Use forEach() when:

You want to apply a function to each element.

You don’t need to break the loop.

Conclusion
Use for loop for index-based iteration.

Use while loop when you don’t know how many times it should run.

Use do...while loop when at least one execution is required.

Use for...of for looping over values of arrays and strings.

Use for...in for iterating over object properties.

Use forEach() for executing a function on each element.

🚀 Hope this clears your doubts on Loops in JavaScript! Let me know if you need more details. 😊
What are Functions in JS? What are the types of function?
01:26
Q57. Difference between named and anonymous functions?
01:48
Q58. What is function expression in JS?
01:11
Q59. What are Arrow Functions in JS? What is it use?
02:14
Q60. What are Callback Functions? What is it use?
02:26
Q61. What is Higher-order function In JS?
02:14
Q62. What is the difference between arguments and parameters?
00:44
Q63. In how many ways can you pass arguments to a function?
01:42
Q64. How do you use default parameters in a function?
00:56
Q65. What is the use of event handling in JS?
02:40

145/411
Q66. What are First-Class functions in JS?
01:25
Q67. What are Pure and Impure functions in JS?
02:57
Q68. What is Function Currying in JS?
02:34
Q69. What are call, apply and bind methods in JS?

JavaScript Functions – Types & Concepts


Q56. What are Functions in JavaScript? What are the types of functions?
A function in JavaScript is a reusable block of code designed to perform a specific task.

Types of Functions in JavaScript:


1. Named Functions – Functions with a name.

2. Anonymous Functions – Functions without a name.

3. Function Expressions – Assigning functions to variables.

4. Arrow Functions – A shorter syntax for writing functions.

5. Callback Functions – Functions passed as arguments to other functions.

6. Higher-Order Functions – Functions that accept or return functions.

7. IIFE (Immediately Invoked Function Expressions) – Functions that execute immediately.

8. Generator Functions – Functions that can pause and resume execution.

9. Pure Functions – Functions that always return the same output for the same input.

Q57. Difference between Named and Anonymous Functions?


Feature Named Function Anonymous Function

Definition Has a name No name (used inside expressions)

Hoisting Hoisted to the top Not hoisted

Use Case Reusable, easy debugging Used as callback or inside expressions

Example:

js

// Named Function
function greet() {
return "Hello!";

146/411
}

// Anonymous Function (stored in variable)


const greetAnonymous = function() {
return "Hello!";
};

Q58. What is Function Expression in JavaScript?


A function expression is when a function is assigned to a variable.

js

const add = function(a, b) {


return a + b;
};
console.log(add(5, 3)); // 8

🔹 Function expressions are not hoisted, unlike named functions.

Q59. What are Arrow Functions in JS? What is its use?


Arrow functions provide a concise syntax for writing functions.

Syntax:

js

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


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

Benefits of Arrow Functions:

✅ Shorter syntax
✅ Does not bind (useful in object methods and callbacks)
this
✅ Implicit return (if there’s only one statement)
🔹 Arrow function vs Regular function (difference in binding):
this

js

147/411
function traditional() {
console.log(this); // Refers to function caller
}

const arrow = () => {


console.log(this); // Refers to the surrounding context (lexical scope)
};

Q60. What are Callback Functions? What is its use?


A callback function is a function passed as an argument to another function.

🔹 Why use Callbacks?


Used for asynchronous operations (e.g., API calls, setTimeout)

Helps in handling events and manipulating arrays ( map , filter )

js

function greet(name, callback) {


console.log("Hello " + name);
callback();
}

function sayBye() {
console.log("Goodbye!");
}

greet("Alice", sayBye);
// Output: Hello Alice
// Goodbye!

Q61. What is a Higher-Order Function in JS?


A higher-order function is a function that either:
✅ Takes another function as an argument, or
✅ Returns a function.
🔹 Example:

148/411
js

function multiplier(factor) {
return function(number) {
return number * factor;
};
}

const double = multiplier(2);


console.log(double(5)); // 10

🔹 Built-in Higher-Order Functions:


map() , filter() , reduce()

Q62. What is the difference between arguments and parameters?


Feature Arguments Parameters

Definition Actual values passed to a function Variables defined in the function declaration

Example sum(5, 10); → 5, 10 are arguments function sum(a, b) → a, b are parameters

js

function sum(a, b) { // a, b → parameters


return a + b;
}
sum(5, 10); // 5, 10 → arguments

Q63. In how many ways can you pass arguments to a function?


1. By value (for primitive types like numbers, strings)

2. By reference (for objects and arrays)

3. Using rest parameters ( ...args )

4. Using default parameters

js

149/411
function sum(...numbers) { // Rest Parameter
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10

Q64. How do you use default parameters in a function?


Default parameters allow functions to have predefined values.

js

function greet(name = "Guest") {


console.log("Hello " + name);
}
greet(); // Hello Guest
greet("Alice"); // Hello Alice

Q65. What is the use of Event Handling in JavaScript?


Event handling allows interaction with users through events like clicks, key presses, form
submissions.

js

document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});

Q66. What are First-Class Functions in JS?


JavaScript treats functions as first-class citizens, meaning:
✅ Functions can be assigned to variables
✅ Functions can be passed as arguments
✅ Functions can return other functions
js

150/411
const sayHello = () => "Hello!";
const greet = sayHello;
console.log(greet()); // "Hello!"

Q67. What are Pure and Impure Functions in JS?


Feature Pure Function Impure Function

Definition Returns same output for same input May return different output for same input

Side Effects No Yes (modifies external state)

Example:

js

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

// Impure Function (modifies global variable)


let total = 0;
function addToTotal(num) {
total += num;
}

Q68. What is Function Currying in JS?


Function currying transforms a function with multiple arguments into nested functions.

js

function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10

151/411
🔹 Use case: Creating reusable functions (e.g., setting tax rates, discounts).

Q69. What are call() , apply() , and bind() in JS?


These methods allow changing the this context of a function.

Method Syntax Use Case

call() fn.call(thisArg, arg1, arg2) Calls a function with a specified this value

apply() fn.apply(thisArg, [argsArray]) Similar to call() , but arguments are passed as an array

bind() fn.bind(thisArg, arg1, arg2) Returns a new function with this permanently set

Example:

js

function greet(city) {
console.log(this.name + " is from " + city);
}

const person = { name: "Alice" };

greet.call(person, "New York"); // Alice is from New York


greet.apply(person, ["London"]); // Alice is from London

const boundFunc = greet.bind(person, "Paris");


boundFunc(); // Alice is from Paris

Conclusion
Functions are the backbone of JavaScript programming. Understanding named vs anonymous
functions, arrow functions, callback functions, higher-order functions, and function methods ( call ,
apply , bind ) is key to mastering JS. 🚀
Let me know if you need further clarifications! 😊
What is a String?
00:19
Q71. What are template literals and string interpolation in strings?
01:31
Q72. Difference between single quotes (''), double quotes ("") &

152/411
backticks('') ?
00:37
Q73. What are some important string operations in JS?
02:10
Q74. What is string immutability?
01:34
Q75. In how many ways you can concatenate strings?

JavaScript Strings – Concepts & Operations


Q70. What is a String?
A string in JavaScript is a sequence of characters enclosed in single ( ' ), double ( " ), or backticks (`)
quotes.

js

let str1 = 'Hello';


let str2 = "World";
let str3 = `JavaScript`;

Strings in JavaScript are immutable, meaning their value cannot be changed after creation.

Q71. What are Template Literals and String Interpolation in JS?


Template literals (introduced in ES6) are enclosed in backticks (`) instead of single or double quotes.
They allow string interpolation and multi-line strings.

String Interpolation (Embedding Variables)

js

let name = "Alice";


let message = `Hello, ${name}!`; // Using ${}
console.log(message); // "Hello, Alice!"

Multi-line Strings

js

let multiLine = `This is


a multi-line string`;
console.log(multiLine);

153/411
Q72. Difference between Single Quotes ( ' ), Double Quotes ( " ), and
Backticks ( ` )?
Feature Single Quotes ( ' ) Double Quotes ( " ) Backticks ( ` )

Usage Common for strings Also common for strings Used for template literals

Interpolation ❌ No ❌ No ✅ Yes ( ${} for variables)

Multi-line Support ❌ No ❌ No ✅ Yes


Example:

js

let single = 'Hello';


let double = "World";
let template = `Hello, ${double}!`; // ✅ Interpolation possible

Q73. What are some important string operations in JS?


Method Description Example

length Returns string length "hello".length // 5

charAt(index) Returns character at index "hello".charAt(1) // 'e'

indexOf(substring) Finds position of substring "hello".indexOf('l') // 2

slice(start, end) Extracts part of a string "hello".slice(1, 3) // 'el'

toUpperCase() Converts to uppercase "hello".toUpperCase() // 'HELLO'

toLowerCase() Converts to lowercase "HELLO".toLowerCase() // 'hello'

trim() Removes whitespace " hello ".trim() // 'hello'

replace(old, new) Replaces part of a string "hello".replace('l', 'x') // 'hexlo'

split(separator) Splits string into array "a,b,c".split(',') // ['a', 'b', 'c']

Q74. What is String Immutability?


Strings in JavaScript are immutable, meaning once created, they cannot be changed.

🔹 Example (Immutable String)

154/411
js

let str = "Hello";


str[0] = "Y"; // ❌ This won't change the string
console.log(str); // "Hello"

To modify a string, you must create a new one:

js

let newStr = "Hello".replace("H", "Y");


console.log(newStr); // "Yello"

Q75. In how many ways can you concatenate strings?


1. Using + Operator (Old Method)

js

let str = "Hello" + " World";


console.log(str); // "Hello World"

2. Using concat() Method

js

let str = "Hello".concat(" World");


console.log(str); // "Hello World"

3. Using Template Literals (Best Practice)

js

let name = "Alice";


let greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Alice!"

4. Using join() with Arrays

js

155/411
let words = ["Hello", "World"];
let sentence = words.join(" ");
console.log(sentence); // "Hello World"

Conclusion
Strings are immutable sequences of characters.

Template literals ( `` ) allow multi-line strings and interpolation.

Various methods like slice() , replace() , and split() help in string manipulation.

Concatenation can be done using + , concat() , or template literals (best approach).

Let me know if you need more details! 🚀


What is DOM? What is the difference between HTML and DOM?
02:31
Q77. How do you select, modify, create and remove DOM
elements?
00:56
Q78. What are selectors in JS?
01:05
Q79. Difference between
getElementById,getElementsByClassName& getElementsByTag?
02:42
Q80. What is the difference between querySelector() and
querySelectorAll()?
01:07
Q81. What are the methods to modify elements properties and
attributes?
00:39
Q82. What is the difference between innerHTML and textContent?
01:24
Q83. How to add and remove properties of HTML elements in the
DOM using JS?
01:07
Q84. How to add and remove style from HTML elements in DOM
using JS?
00:56
Q85. Create new elements in DOM using JS?
02:20

156/411
Q86. What is the difference between createElement() and
createTextNode()?

JavaScript DOM (Document Object Model) - Concepts &


Operations
Q76. What is DOM? What is the difference between HTML and DOM?

What is DOM?

The Document Object Model (DOM) is a programming interface for web documents.

It represents the HTML structure as a tree-like hierarchy that can be accessed and manipulated
using JavaScript.

Difference Between HTML & DOM

Feature HTML DOM

Definition Static structure of a Dynamic representation of the webpage


webpage

Type Markup Language API (Programmatic Interface)

Modification Cannot be modified Can be modified using JS


directly

Example <p>Hello</p> (HTML document.querySelector("p").innerText = "Hi"; (DOM


Code) Manipulation)

Q77. How do you Select, Modify, Create, and Remove DOM Elements?
1. Select Elements

js

let element = document.getElementById("myId"); // Select by ID

2. Modify Elements

js

element.innerHTML = "Updated Text"; // Change content

3. Create Elements

js

157/411
let newDiv = document.createElement("div");
newDiv.innerText = "New Element";
document.body.appendChild(newDiv);

4. Remove Elements

js

document.body.removeChild(newDiv);

Q78. What are Selectors in JS?


Selectors help you find and select elements in the DOM.

Selector Method Description Example

getElementById() Selects element by id document.getElementById("myId")

getElementsByClassName() Selects elements by class document.getElementsByClassName("myClass")

getElementsByTagName() Selects elements by tag document.getElementsByTagName("div")


name

querySelector() Selects first matching document.querySelector(".myClass")


element

querySelectorAll() Selects all matching document.querySelectorAll("p")


elements

Q79. Difference Between getElementById() , getElementsByClassName() , and


getElementsByTagName() ?

Method Returns Example

getElementById("id") Single Element document.getElementById("header")

getElementsByClassName("class") HTMLCollection (Live) document.getElementsByClassName("box")

getElementsByTagName("tag") HTMLCollection (Live) document.getElementsByTagName("p")

158/411
Q80. What is the Difference Between querySelector() and
querySelectorAll() ?

Method Returns Example

querySelector("selector") First Matching Element document.querySelector(".box")

querySelectorAll("selector") All Matching Elements (NodeList) document.querySelectorAll(".box")

Q81. Methods to Modify Element Properties and Attributes


1. Modify Property

js

document.getElementById("myDiv").innerHTML = "Updated Content";

2. Modify Attribute

js

document.getElementById("myInput").setAttribute("type", "password");

Q82. Difference Between innerHTML and textContent


Feature innerHTML textContent

Returns HTML + Text Only Text

Security Vulnerable to XSS Safer

Example div.innerHTML = "<b>Bold</b>" div.textContent = "<b>Bold</b>" (Shows as text)

Q83. How to Add and Remove Properties of HTML Elements in the DOM Using
JS?
1. Add Property

js

159/411
document.getElementById("myDiv").customProperty = "Custom Value";

2. Remove Property

js

delete document.getElementById("myDiv").customProperty;

Q84. How to Add and Remove Styles from HTML Elements Using JS?
1. Add Style

js

document.getElementById("myDiv").style.color = "red";

2. Remove Style

js

document.getElementById("myDiv").style.removeProperty("color");

Q85. Create New Elements in DOM Using JS


js

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


newElement.textContent = "Hello, World!";
document.body.appendChild(newElement);

Q86. Difference Between createElement() and createTextNode()


Method Purpose Example

createElement("tag") Creates a new HTML element document.createElement("div")

createTextNode("text") Creates text content (no HTML) document.createTextNode("Hello")

160/411
Conclusion
The DOM represents HTML elements as a tree structure that JS can manipulate.

Use selectors ( getElementById() , querySelector() ) to find elements.

Modify properties, attributes, and styles dynamically using JS.

Use createElement() for elements and createTextNode() for text content.

🚀 Let me know if you need more details!


What is Error Handling in JS?
01:16
Q88. What is the role of finally block in JS?
01:21
Q89. What is the purpose of the throw statement in JS?
01:30
Q90. What is Error propagation in JS?
00:38
Q91. What are the best practices for error handling?
01:02
Q92. What are the different types of errors In JS?

Error Handling in JavaScript - Concepts & Best Practices

Q87. What is Error Handling in JavaScript?


Error handling in JavaScript refers to the process of detecting, catching, and managing errors to
prevent a program from crashing.

JavaScript provides the try...catch mechanism for handling errors gracefully.

Example of Error Handling

js

try {
let result = 10 / 0; // No error, but may cause unexpected behavior
console.log(result);

let x = y; // ReferenceError: y is not defined


} catch (error) {
console.error("An error occurred:", error.message);
}

161/411
Q88. What is the Role of the finally Block in JavaScript?
The finally block executes always, regardless of whether an error occurs or not.

It is used for cleanup operations like closing connections or releasing resources.

Example of finally Block

js

try {
console.log("Trying...");
throw new Error("Something went wrong!");
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("Finally block executed.");
}

Output:

vbnet

Trying...
Caught an error: Something went wrong!
Finally block executed.

Q89. What is the Purpose of the throw Statement in JavaScript?


The throw statement is used to create custom errors.

It allows developers to manually throw an error with a custom message.

Example of throw Statement

js

function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or above!");
}
console.log("Access granted.");
}

162/411
try {
checkAge(16);
} catch (error) {
console.error(error.message);
}

Output:

nginx

Age must be 18 or above!

Q90. What is Error Propagation in JavaScript?


Error propagation refers to the process of bubbling up an error from a function to the calling
function until it is handled.

If not caught at any level, the program may crash.

Example of Error Propagation

js

function level1() {
level2(); // Calls another function
}

function level2() {
throw new Error("Error from level2"); // Error propagates
}

try {
level1();
} catch (error) {
console.error("Caught an error:", error.message);
}

Output:

vbnet

Caught an error: Error from level2

163/411
Q91. Best Practices for Error Handling in JavaScript
1. Use try...catch for expected errors

Example: Handling API request failures.

2. Always use finally for cleanup

Example: Closing database connections.

3. Use specific error types ( TypeError , ReferenceError )

js

try {
let num = null;
console.log(num.length); // TypeError
} catch (error) {
if (error instanceof TypeError) {
console.error("Type Error:", error.message);
}
}

4. Avoid using throw for control flow

Use throw for critical errors only.

5. Use logging tools for error tracking

Example: console.error() , Sentry , LogRocket .

Q92. Different Types of Errors in JavaScript


Error Type Description Example

ReferenceError Accessing an undefined variable console.log(x); // x is not defined

TypeError Performing an invalid operation on a type null.toUpperCase();

SyntaxError Incorrect syntax in the code console.log("Hello)

RangeError Using a number outside its allowed range new Array(-1);

URIError Invalid use of URI functions decodeURIComponent("%");

164/411
Summary
Error Handling is crucial for preventing program crashes.

Use try...catch to handle runtime errors.

finally ensures code execution regardless of errors.

Use throw to create custom errors.

Error propagation occurs when an error bubbles up through function calls.

Follow best practices to write maintainable and error-free JavaScript.

🚀 Let me know if you need more details!


What are Objects in JS?
02:00
Q94. In how many ways we can create an object?
01:36
Q95. What is the difference between an array and an object?
00:57
Q96. How do you add or modify or delete properties of an object?
00:37
Q97. Explain the difference between dot notation and bracket
notation?
01:24
Q98. What are some common methods to iterate over the
properties of an object?
01:32
Q99. How do you check if a property exists in an object?
01:23
Q100. How do you clone or copy an object?
01:48
Q101. What is the difference between deep copy and shallow copy
in JS?
02:46
Q102. What is Set Object in JS?
02:27
Q103. What is Map Object in JS?
01:26
Q104. What is the difference between Map and Object in JS?

Objects in JavaScript - Concepts & Best Practices

Q93. What are Objects in JavaScript?

165/411
An object in JavaScript is a collection of key-value pairs where keys are strings (or Symbols) and
values can be any data type.

Objects allow storing and organizing related data.

Example of an Object

js

const person = {
name: "John",
age: 30,
isStudent: false,
greet: function () {
console.log("Hello, " + this.name);
},
};

console.log(person.name); // John
person.greet(); // Hello, John

Q94. How Many Ways Can We Create an Object?


There are 4 main ways to create an object in JavaScript:

1️⃣ Using Object Literals (Most Common)


js

const user = { name: "Alice", age: 25 };

2️⃣ Using new Object() Constructor

js

const user = new Object();


user.name = "Alice";
user.age = 25;

3️⃣ Using Object.create()


js

const userPrototype = { greet: function () { console.log("Hello!"); } };


const user = Object.create(userPrototype);

166/411
user.name = "Alice";

4️⃣ Using Constructor Function


js

function User(name, age) {


this.name = name;
this.age = age;
}

const user = new User("Alice", 25);

Q95. Difference Between an Array and an Object


Feature Array Object

Indexed by Numeric index Named keys (properties)

Use Case Ordered data Key-value pairs

Iteration Loops (for, forEach, map) for...in , Object.keys()

Example [1, 2, 3] { name: "Alice", age: 25 }

Q96. How to Add, Modify, and Delete Properties of an Object?

Adding or Modifying Properties

js

const user = { name: "Alice" };


user.age = 25; // Adding a new property
user.name = "Bob"; // Modifying an existing property

Deleting a Property

js

delete user.age;
console.log(user); // { name: "Bob" }

167/411
Q97. Dot Notation vs. Bracket Notation
Feature Dot Notation Bracket Notation

Usage obj.key obj["key"]

When to Use When the key is a valid identifier When the key is dynamic or not a valid identifier

Example person.name person["first-name"]

Example

js

const person = { "first-name": "Alice", age: 25 };

console.log(person.age); // ✅ Dot notation works


console.log(person["first-name"]); // ✅ Must use bracket notation

Q98. Common Ways to Iterate Over Object Properties


1️⃣ Using for...in Loop

js

const user = { name: "Alice", age: 25 };


for (let key in user) {
console.log(key, user[key]);
}

2️⃣ Using Object.keys()

js

Object.keys(user).forEach(key => console.log(key, user[key]));

3️⃣ Using Object.entries()

js

Object.entries(user).forEach(([key, value]) => console.log(key, value));

168/411
Q99. How to Check if a Property Exists in an Object?
1️⃣ Using in Operator

js

console.log("name" in user); // true

2️⃣ Using hasOwnProperty()

js

console.log(user.hasOwnProperty("age")); // true

3️⃣ Using Object.hasOwn() (ES2022)

js

console.log(Object.hasOwn(user, "age")); // true

Q100. How to Clone or Copy an Object?


1️⃣ Using Spread Operator ( ... )

js

const newUser = { ...user };

2️⃣ Using Object.assign()

js

const newUser = Object.assign({}, user);

3️⃣ Using JSON.parse(JSON.stringify(obj)) (For Deep Copy)

js

const deepCopy = JSON.parse(JSON.stringify(user));

Q101. Difference Between Deep Copy and Shallow Copy

169/411
Type Shallow Copy Deep Copy

Definition Copies references of nested objects Creates a completely new object

Method ...spread , Object.assign() JSON.parse(JSON.stringify(obj)) , structuredClone()

Example

js

let obj1 = { a: { b: 10 } };
let obj2 = { ...obj1 }; // Shallow copy
obj2.a.b = 20; // Changes obj1 too!

js

let obj3 = JSON.parse(JSON.stringify(obj1)); // Deep copy


obj3.a.b = 30; // obj1 remains unchanged

Q102. What is a Set Object in JavaScript?


A Set is a collection of unique values.

Example of Set

js

const numbers = new Set([1, 2, 3, 3, 4]);


console.log(numbers); // { 1, 2, 3, 4 }

✅ Operations on Sets
js

numbers.add(5); // Adds a value


numbers.delete(2); // Deletes a value
console.log(numbers.has(3)); // true

Q103. What is a Map Object in JavaScript?


A Map is a key-value pair collection where keys can be any data type.

170/411
Example of Map

js

const userMap = new Map();


userMap.set("name", "Alice");
userMap.set(1, "Number as key");
console.log(userMap.get("name")); // Alice

✅ Operations on Maps
js

console.log(userMap.has("name")); // true
console.log(userMap.size); // 2

Q104. Difference Between Map and Object


Feature Map Object

Key Types Any (string, number, object) Strings (or Symbols)

Ordering Keys are ordered Keys are unordered

Iteration map.forEach() , for...of for...in , Object.keys()

Performance Faster for frequent additions/removals Slower due to property access overhead

Summary
Objects store data in key-value pairs.

Ways to create objects: Object literals, constructors, Object.create() , new Object() .

Modify/Delete properties using dot/bracket notation.

Iterate objects using for...in , Object.keys() , and Object.entries() .

Clone objects using spread ( ... ) and Object.assign() .

Shallow Copy vs. Deep Copy: Deep copy creates a full independent copy.

Set & Map: Set stores unique values, Map allows flexible key types.

🚀 Let me know if you need more examples!

171/411
What are Events? How are events triggered?
01:40
Q106. What are the types of events in JS?
01:05
Q107. What is Event Object in JS?
02:02
Q108. What is Event Delegation in JS?
02:01
Q109. What is Event Bubbling In JS?
01:40
Q110. How can you stop event propagation or event bubbling in
JS?
01:10
Q111. What is Event Capturing in JS?
01:42
Q112. What is the purpose of the event.preventDefault() method in
JS?
01:08
Q113. What is the use of "this" keyword in the context of event
handling in JS?
00:38
Q114. How to remove an event handler from an element in JS?

JavaScript Events - Concepts & Best Practices

Q105. What are Events? How are events triggered?


Events in JavaScript are actions or occurrences that happen in the browser, such as clicks,
keypresses, mouse movements, etc.

Events can be triggered by the user (e.g., clicking a button) or programmatically (e.g., using
dispatchEvent() ).

✅ Example: User-triggered Event


js

document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});

✅ Example: Programmatically Triggering an Event


js

172/411
const event = new Event("click");
document.getElementById("btn").dispatchEvent(event);

Q106. What are the Types of Events in JavaScript?


JavaScript events are categorized into different types:

1️⃣ Mouse Events


click , dblclick , mousedown , mouseup , mousemove , mouseover , mouseout

2️⃣ Keyboard Events


keydown , keyup , keypress

3️⃣ Form Events


submit , change , focus , blur , reset

4️⃣ Window Events


load , unload , resize , scroll

5️⃣ Clipboard Events


copy , cut , paste

6️⃣ Touch Events (Mobile)


touchstart , touchmove , touchend

Q107. What is the Event Object in JavaScript?


The event object ( event ) contains details about the event that occurred, such as:

event.type : Type of event (e.g., "click").

event.target : Element that triggered the event.

event.clientX / event.clientY : Mouse position.

✅ Example: Using the Event Object


js

173/411
document.getElementById("btn").addEventListener("click", function(event) {
console.log("Event Type:", event.type);
console.log("Clicked Element:", event.target);
});

Q108. What is Event Delegation in JavaScript?


Event Delegation is a technique where a parent element listens for events on its children.

Useful when handling events on dynamically created elements.

✅ Example: Event Delegation


js

document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.classList.contains("child")) {
alert("Child element clicked!");
}
});

✅ Why use Event Delegation?


Reduces memory usage (fewer event listeners).

Useful for dynamically added elements.

Q109. What is Event Bubbling in JavaScript?


Event Bubbling means that an event starts at the target element and bubbles up to its parent
elements.

✅ Example: Event Bubbling


html

<div id="parent">
<button id="child">Click Me</button>
</div>

<script>

174/411
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked!");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked!");
});
</script>

✅ Output on clicking the button:


nginx

Child clicked!
Parent clicked!

(The event bubbles from #child to #parent .)


Q110. How to Stop Event Propagation in JavaScript?
Use event.stopPropagation() to stop bubbling.

✅ Example: Stopping Event Bubbling


js

document.getElementById("child").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Child clicked, but won't bubble up!");
});

Q111. What is Event Capturing in JavaScript?


Event Capturing (Trickling Phase) happens before bubbling.

Events travel from the root element down to the target element.

✅ Example: Event Capturing


js

document.getElementById("parent").addEventListener("click", function() {
console.log("Parent clicked in capturing phase!");
}, true); // `true` enables capturing phase

175/411
✅ Output when clicking child button:
nginx

Parent clicked in capturing phase!


Child clicked!

(Capturing happens before bubbling.)


Q112. What is the purpose of event.preventDefault() ?
It prevents the default behavior of an element (like form submission, link redirection, etc.).

✅ Example: Preventing Form Submission


js

document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submission prevented!");
});

Q113. What is the use of this in event handling?


Inside an event handler, this refers to the element that triggered the event.

✅ Example: Using this

js

document.getElementById("btn").addEventListener("click", function() {
console.log(this.id); // Logs "btn"
});

Q114. How to Remove an Event Handler in JavaScript?


Use removeEventListener() to remove an event.

✅ Example: Removing an Event Listener

176/411
js

function greet() {
alert("Hello!");
}

document.getElementById("btn").addEventListener("click", greet);
document.getElementById("btn").removeEventListener("click", greet);

Summary
Concept Explanation

Events Actions like clicks, keypresses, etc.

Types of Events Mouse, Keyboard, Form, Window, Clipboard, Touch

Event Object Provides details like event.type , event.target

Event Delegation Parent element listens for child events

Event Bubbling Events propagate up from the target

Stop Bubbling Use event.stopPropagation()

Event Capturing Events propagate down (use { capture: true } )

Prevent Default event.preventDefault() stops default behavior

this in Events Refers to the element that triggered the event

Remove Event Use removeEventListener()

🚀 Let me know if you need more details!


Explain the concept of Lexical Scoping?
01:16
Q116. What is Closure?
01:53
Q117. What are the benefits of Closures?
04:34
Q118. What is the concept of Encapsulation in the context of
closures?
01:21
Q119. What are the disadvantage or limitations of Closures?
01:02
Q120. How can you release the variable references or closures
from memory?
00:26

177/411
Q121. What is the difference between a Regular Function and a
Closure?

JavaScript Scope, Closures & Encapsulation

Q115. Explain the concept of Lexical Scoping?


Lexical Scoping means that a function remembers the scope where it was defined, not where it
was executed.

Inner functions can access variables from their outer function but not vice versa.

✅ Example: Lexical Scoping


js

function outer() {
let outerVar = "I am outer!";

function inner() {
console.log(outerVar); // ✅ Can access outerVar
}

inner();
}

outer();

📌 Key Takeaway:
The inner() function remembers the outerVar even though it is called inside outer() .

Q116. What is a Closure?


Closure is a function that remembers variables from its lexical scope even when executed outside
of its original scope.

✅ Example: Closure
js

function outer() {
let count = 0; // Private variable

178/411
return function inner() {
count++; // Closure remembers `count`
console.log(count);
};
}

const counter = outer();


counter(); // Output: 1
counter(); // Output: 2

📌 Why?
The inner() function remembers count , even after outer() has finished execution.

Q117. What are the Benefits of Closures?


1️⃣ Data Privacy (Encapsulation) – Variables inside closures cannot be accessed from outside.
2️⃣ Memoization (Caching Results) – Storing previous results for optimization.
3️⃣ Event Handlers & Callbacks – Closures allow event listeners to access outer function variables.
4️⃣ Function Factories – Used to create multiple functions with different behaviors.
✅ Example: Data Privacy (Encapsulation)
js

function bankAccount(initialBalance) {
let balance = initialBalance;

return {
deposit(amount) {
balance += amount;
console.log(`Balance: ${balance}`);
},
withdraw(amount) {
if (amount <= balance) {
balance -= amount;
console.log(`Balance: ${balance}`);
} else {
console.log("Insufficient funds!");
}
}
};
}

179/411
const account = bankAccount(1000);
account.deposit(500); // Balance: 1500
account.withdraw(200); // Balance: 1300
console.log(account.balance); // ❌ Undefined (Encapsulated)

Q118. What is Encapsulation in the context of Closures?


Encapsulation means hiding variables inside a function, so they can only be accessed via specific
methods.

✅ Example: Encapsulation with Closures


js

function counter() {
let count = 0; // Private variable

return {
increment() { count++; console.log(count); },
decrement() { count--; console.log(count); }
};
}

const myCounter = counter();


myCounter.increment(); // Output: 1
myCounter.decrement(); // Output: 0
console.log(myCounter.count); // ❌ Undefined
📌 Key Takeaway:
The count variable is private because it's inside the closure.

It can only be modified using increment() and decrement() .

Q119. What are the Disadvantages or Limitations of Closures?


1️⃣ Memory Consumption – Closures hold variables in memory, preventing garbage collection.
2️⃣ Performance Issues – Unnecessary closures in loops or heavy computations slow down execution.
3️⃣ Debugging Complexity – Hard to track memory leaks caused by closures.
✅ Example: Potential Memory Issue

180/411
js

function createClosure() {
let largeArray = new Array(1000000).fill("data"); // Large memory usage
return function() {
console.log(largeArray.length);
};
}

const memoryLeak = createClosure(); // Closure holds reference to `largeArray`

📌 Fix: Manually clear the reference when no longer needed.


Q120. How can you Release Variable References or Closures from Memory?
1️⃣ Assign null to variables to free memory. 2️⃣ Use WeakMap for automatic garbage collection. 3️⃣
Avoid unnecessary closures inside loops.

✅ Example: Releasing Memory


js

let closureFunc = createClosure();


closureFunc = null; // ✅ Releases memory for `largeArray`

Q121. What is the Difference between a Regular Function and a Closure?


Feature Regular Function Closure

Scope Access Can access only its own variables Can access outer function variables

Memory Usage Releases memory when function completes Holds variables in memory

Encapsulation No data privacy Provides private variables

Use Case Simple function calls Data privacy, event handlers, caching

✅ Example: Regular Function vs Closure


js

// Regular Function
function regular() {
let count = 0;
count++;
console.log(count);

181/411
}
regular(); // Output: 1
regular(); // Output: 1 (doesn't remember previous count)

// Closure
function closure() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const counter = closure();
counter(); // Output: 1
counter(); // Output: 2 (remembers previous count)

📌 Key Difference:
A regular function forgets its variables after execution.

A closure remembers and retains its variables even after execution.

Summary of Closures & Lexical Scoping


Concept Explanation

Lexical Scope Functions remember where they were defined.

Closures Functions that keep access to outer function variables even after execution.

Encapsulation Closures hide variables and provide controlled access.

Benefits of Closures Data privacy, event handling, caching, function factories.

Limitations Higher memory usage, performance issues, harder debugging.

Releasing Memory Use null , WeakMap , and avoid unnecessary closures.

🚀 Closures are a powerful feature in JavaScript! Let me know if you need more examples.
What is asynchronous programming in JS? What is its use?
03:27
Q123. What is the difference between synchronous and
asynchronous programming?
01:39
Q124. What are the techniques for achieving asynchronous
operations in JS?
00:37

182/411
Q125. What is setTimeout()? How is it used to handle
asynchronous operations?
02:09
Q126. What is setInterval()? How is it used to handle asynchronous
operations?
01:33
Q127. What is the role of callbacks in fetching API data
asynchronously?
02:27
Q128. What is callback hell? How can it be avoided?

Asynchronous Programming in JavaScript

Q122. What is Asynchronous Programming in JS? What is its use?


Asynchronous programming allows JavaScript to execute non-blocking operations, meaning it
doesn’t wait for one task to complete before starting another.

This is crucial for handling tasks like API calls, file operations, and timers without freezing the UI.

✅ Example: Asynchronous Code Using setTimeout()

js

console.log("Start");

setTimeout(() => {
console.log("Asynchronous Task");
}, 2000);

console.log("End");

📌 Output:
pgsql

Start
End
Asynchronous Task (after 2 seconds)

👉 Use Cases of Asynchronous Programming: 1️⃣ Fetching API data (AJAX, Fetch API, Axios).
2️⃣ Handling user interactions without UI lag.
3️⃣ Running timers ( ,
setTimeout ).
setInterval
4️⃣ Working with files, databases, or external servers.

183/411
Q123. What is the Difference Between Synchronous and Asynchronous
Programming?
Feature Synchronous Asynchronous

Execution Order Line-by-line (Blocking) Non-blocking (Does not wait)

Performance Slower, as it waits for each task to complete Faster, as multiple tasks run in parallel

Use Cases Simple calculations, loops API calls, file handling, animations

Example console.log() , for loop setTimeout() , fetch() , Promises

✅ Example: Synchronous Execution


js

console.log("Task 1");
console.log("Task 2");
console.log("Task 3");

Output:

arduino

Task 1
Task 2
Task 3

✅ Example: Asynchronous Execution


js

console.log("Task 1");

setTimeout(() => {
console.log("Task 2 (Delayed)");
}, 2000);

console.log("Task 3");

Output:

arduino

184/411
Task 1
Task 3
Task 2 (Delayed)

📌 Key Difference:
Synchronous: Blocks execution until a task finishes.

Asynchronous: Moves to the next task immediately while waiting for previous ones.

Q124. What are the Techniques for Achieving Asynchronous Operations in JS?
1️⃣ Callbacks – Pass a function as an argument to be executed later.
2️⃣ Promises – Handle async operations with .then()and .
.catch()
3️⃣ Async/Await – A modern approach for writing cleaner async code.
4️⃣ Web APIs – setTimeout , ,
setInterval ,
fetch() .
XMLHttpRequest

Q125. What is setTimeout() ? How is it Used for Asynchronous Operations?


setTimeout() is a JavaScript function that executes a callback function after a specified delay.

✅ Example: Using setTimeout()

js

console.log("Start");

setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);

console.log("End");

📌 Output:
pgsql

Start
End
Executed after 2 seconds

185/411
💡 Use Cases:
✔ Delaying API calls.
✔ Creating loading effects.
✔ Scheduling functions for later execution.

Q126. What is setInterval() ? How is it Used for Asynchronous Operations?


setInterval() executes a function repeatedly at a fixed interval.

✅ Example: Using setInterval()

js

let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 5) clearInterval(intervalId); // Stops after 5 times
}, 1000);

📌 Output:
makefile

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

💡 Use Cases:
✔ Updating UI dynamically.
✔ Creating countdown timers.
✔ Refreshing API data periodically.

Q127. What is the Role of Callbacks in Fetching API Data Asynchronously?


Callbacks are functions passed as arguments to other functions, allowing us to handle
asynchronous operations like API calls.

186/411
✅ Example: Using a Callback in an API Request
js

function fetchData(callback) {
setTimeout(() => {
callback("Fetched Data");
}, 2000);
}

fetchData((data) => {
console.log(data); // Output: Fetched Data (after 2 sec)
});

📌 Why Use Callbacks?


✔ Ensures code runs after async tasks finish.
✔ Useful for event handling, API requests, and file operations.

Q128. What is Callback Hell? How Can it be Avoided?


📌 Callback Hell occurs when multiple nested callbacks make code hard to read and maintain.
❌ Example of Callback Hell:
js

setTimeout(() => {
console.log("Task 1");
setTimeout(() => {
console.log("Task 2");
setTimeout(() => {
console.log("Task 3");
}, 1000);
}, 1000);
}, 1000);

🔴 Problems with Callback Hell:


Hard to read and debug.

Difficult to maintain and scale.

Prone to errors and logic issues.

187/411
✅ How to Avoid Callback Hell? ✔ Use Promises – Replace nested callbacks with .then()
✔ Use Async/Await – Write clean and readable async code

✅ Solution 1: Using Promises


js

function asyncTask(message, delay) {


return new Promise((resolve) => {
setTimeout(() => resolve(message), delay);
});
}

asyncTask("Task 1", 1000)


.then((msg) => {
console.log(msg);
return asyncTask("Task 2", 1000);
})
.then((msg) => {
console.log(msg);
return asyncTask("Task 3", 1000);
})
.then((msg) => console.log(msg));

✅ Solution 2: Using Async/Await (Best Approach)


js

async function executeTasks() {


console.log(await asyncTask("Task 1", 1000));
console.log(await asyncTask("Task 2", 1000));
console.log(await asyncTask("Task 3", 1000));
}

executeTasks();

📌 Key Takeaways:
Callback Hell: Happens when multiple nested callbacks make code unreadable.

Solution: Use Promises or Async/Await to write cleaner async code.

🔹 Summary of Asynchronous Programming in JavaScript

188/411
Concept Description

Asynchronous Programming Allows JavaScript to handle non-blocking tasks.

Synchronous vs. Asynchronous Synchronous blocks execution, Asynchronous does not.

Techniques for Async Code Callbacks, Promises, Async/Await, Web APIs.

setTimeout() Runs a function after a delay.

setInterval() Runs a function repeatedly at a fixed interval.

Callbacks in API Requests Used to execute functions after fetching data.

Callback Hell Nested callbacks make code unreadable.

Avoiding Callback Hell Use Promises or Async/Await for cleaner code.

🚀 Next Steps: Learn Promises and Async/Await in-depth! Need more examples? Let me know!
Let's dive deeper into Promises and Async/Await in JavaScript! 🚀

🔹 Promises in JavaScript
What is a Promise?
A Promise is an object that represents the eventual completion or failure of an asynchronous
operation.

States of a Promise:
1️⃣ Pending – Initial state, operation not yet completed.
2️⃣ Fulfilled – Operation completed successfully.
3️⃣ Rejected – Operation failed.

✅ Creating a Promise
js

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


let success = true; // Change to false to test rejection
setTimeout(() => {
if (success) {
resolve("Promise Resolved!✅");
} else {
reject("Promise Rejected! ❌");

189/411
}
}, 2000);
});

// Handling the Promise


myPromise
.then((message) => console.log(message)) // Executes when resolved
.catch((error) => console.log(error)) // Executes when rejected
.finally(() => console.log("Execution Completed! 🎉"));
📌 Output (if success is true ):

javascript

Promise Resolved! ✅
Execution Completed! 🎉
📌 Output (if success is false ):

javascript

Promise Rejected! ❌
Execution Completed! 🎉

✅ Chaining Multiple Promises


js

function asyncTask(message, delay) {


return new Promise((resolve) => {
setTimeout(() => resolve(message), delay);
});
}

asyncTask("Task 1", 1000)


.then((msg) => {
console.log(msg);
return asyncTask("Task 2", 1000);
})
.then((msg) => {
console.log(msg);
return asyncTask("Task 3", 1000);
})

190/411
.then((msg) => console.log(msg))
.catch((err) => console.error(err)); // Handles any errors

📌 Output:
arduino

Task 1
Task 2
Task 3

🔹 Why Use Promises? ✔ Helps avoid callback hell


✔ Provides better error handling
✔ Can be chained to run sequential tasks

🔹 Async/Await in JavaScript
What is Async/Await?
async and await are modern ways to handle asynchronous operations without using .then() .

It makes asynchronous code look like synchronous code, improving readability.

✅ Converting a Promise into Async/Await


js

async function fetchData() {


try {
let response = await asyncTask("Fetching Data...", 2000);
console.log(response);

let processedData = await asyncTask("Processing Data...", 2000);


console.log(processedData);

console.log("Data Fetching Complete!");


} catch (error) {
console.log("Error:", error);
}
}

fetchData();

📌 Output:

191/411
nginx

Fetching Data...
Processing Data...
Data Fetching Complete!

🔹 Why Use Async/Await? ✔ Cleaner syntax (no .then() chaining).


✔ Easier to read & maintain.
✔ Built-in error handling using try/catch .

🔹 Handling Multiple Promises in Parallel


✅ Promise.all()

Executes multiple promises in parallel and waits for all to resolve.

js

let p1 = asyncTask("Task 1", 2000);


let p2 = asyncTask("Task 2", 3000);
let p3 = asyncTask("Task 3", 1000);

Promise.all([p1, p2, p3]).then((results) => console.log(results));

📌 Output (after 3 sec, the longest time):


css

["Task 1", "Task 2", "Task 3"]

🔹 When to Use? ✔ When you need all tasks to complete before moving forward.

✅ Promise.race()

Returns the first resolved/rejected promise.

js

Promise.race([p1, p2, p3]).then((result) => console.log(result));

📌 Output (after 1 sec, the fastest promise):


192/411
arduino

Task 3

🔹 When to Use? ✔ When you want the fastest response (e.g., loading indicator).

🔹 Summary of Promises vs Async/Await


Feature Promises Async/Await

Readability Harder with .then() chaining Cleaner and easier

Error Handling Uses .catch() Uses try/catch

Execution Uses .then() for async handling Looks like synchronous code

Best For API calls, chaining async tasks Cleaner, maintainable async code

🚀 Best Practices for Asynchronous Code


✔ Use async/await for readability.
✔ Use try/catch for error handling.
✔ Use Promise.all() for parallel tasks.
✔ Avoid callback hell, use promises instead.

🔥 Need more examples? Want real-world use cases? Let me know! 😊


Let's explore some real-world use cases of Promises and Async/Await in JavaScript! 🚀

🔹 Real-World Use Cases of Promises and Async/Await


1️⃣ Fetching Data from an API
✅ Suppose you are fetching user data from an API using fetch() , which returns a Promise.

js

193/411
async function fetchUserData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await response.json();
console.log("User Data:", user);
} catch (error) {
console.error("Error fetching user data:", error);
}
}

fetchUserData();

📌 Output (Example):
json

User Data: {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]"
}

🔹 Why use await fetch() ? ✔ Avoids .then() nesting.


✔ Makes API call look like synchronous code.

2️⃣ Making Multiple API Calls Sequentially


✅ Suppose you need to fetch user details first, then fetch user posts.
js

async function fetchUserAndPosts() {


try {
let userResponse = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await userResponse.json();
console.log("User:", user);

let postsResponse = await fetch(`https://jsonplaceholder.typicode.com/posts?


userId=${user.id}`);
let posts = await postsResponse.json();
console.log("User's Posts:", posts);
} catch (error) {

194/411
console.error("Error fetching data:", error);
}
}

fetchUserAndPosts();

📌 Output (Example):
yaml

User: { id: 1, name: "Leanne Graham", ... }


User's Posts: [{ id: 1, title: "Post 1" }, { id: 2, title: "Post 2" }, ...]

🔹 Why sequential?
✔ We need user ID before fetching user posts.

3️⃣ Running Multiple API Calls in Parallel


✅ Suppose you need to fetch data from multiple APIs at the same time.
js

async function fetchMultipleData() {


try {
let [users, posts] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users").then(res => res.json()),
fetch("https://jsonplaceholder.typicode.com/posts").then(res => res.json())
]);

console.log("Users:", users);
console.log("Posts:", posts);
} catch (error) {
console.error("Error fetching data:", error);
}
}

fetchMultipleData();

📌 Why Promise.all() ?
✔ Fetches users and posts in parallel (faster performance).
✔ Saves time by not waiting for each request to complete before starting the next.

195/411
4️⃣ Handling Timeouts with setTimeout using Promises

✅ Suppose you need to simulate a delay before executing a task.


js

function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function fetchDataWithDelay() {


console.log("Fetching data...");
await delay(3000); // 3-second delay
console.log("Data fetched! ✅");
}

fetchDataWithDelay();

📌 Output:
kotlin

Fetching data...
(Data appears after 3 seconds)
Data fetched! ✅
🔹 Why use Promises with setTimeout ?
✔ Allows async operations with controlled delays.

5️⃣ Retrying Failed API Calls ( Promise.retry() )

✅ Suppose an API call fails due to a network issue, and we want to retry it 3 times before giving up.
js

async function fetchWithRetry(url, retries = 3) {


for (let i = 0; i < retries; i++) {
try {
let response = await fetch(url);
if (!response.ok) throw new Error(`Attempt ${i + 1} failed`);
return await response.json();
} catch (error) {
console.log(error.message);
if (i === retries - 1) throw new Error("All retries failed! ❌");
}

196/411
}
}

fetchWithRetry("https://jsonplaceholder.typicode.com/users/1")
.then(data => console.log("Fetched Data:", data))
.catch(error => console.error(error.message));

📌 Why retry logic?


✔ Handles intermittent network failures.
✔ Prevents app crashes due to temporary server issues.

6️⃣ Avoiding Callback Hell


✅ Suppose you have nested asynchronous operations (callback hell scenario):
❌ Using Callbacks (Bad Example):
js

function getUser(callback) {
setTimeout(() => {
console.log("User fetched");
callback();
}, 1000);
}

function getPosts(callback) {
setTimeout(() => {
console.log("User's posts fetched");
callback();
}, 1000);
}

getUser(() => {
getPosts(() => {
console.log("All tasks completed!");
});
});

😵 Problem?
Hard to read & maintain due to nested callbacks.

✅ Using Async/Await (Better Approach):

197/411
js

async function fetchUserData() {


await new Promise(resolve => setTimeout(resolve, 1000));
console.log("User fetched");

await new Promise(resolve => setTimeout(resolve, 1000));


console.log("User's posts fetched");

console.log("All tasks completed!");


}

fetchUserData();

✔ Easier to read & maintain!

🔹 Summary & Best Practices


✔ Use async/await instead of .then() for better readability.
✔ Use Promise.all() for parallel execution when tasks are independent.
✔ Use Promise.retry() to handle API failures.
✔ Use Promises with setTimeout for delayed execution.
✔ Use try/catch to handle errors properly.
✔ Avoid Callback Hell by using Promises or Async/Await.

🚀 Need more examples or specific scenarios? Let me know! 😊


What are Promises in JavaScript?
02:45
Q130. How to implement Promises in JavaScript?
02:30
Q131. When to use Promises in real applications?
00:47
Q132. What is the use of Promise.all() method?
02:11
Q133. What is the use of Promise.race() method?
01:23
Q134. What is the difference between Promise.all() and
Promise.race()?

198/411
🔹 Promises in JavaScript
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value.

Example of a Promise:

js

const myPromise = new Promise((resolve, reject) => {


let success = true;
setTimeout(() => {
if (success) {
✅ Promise resolved successfully!");
resolve("
} else {
reject("❌ Promise rejected due to an error.");
}
}, 2000);
});

myPromise
.then(result => console.log(result))
.catch(error => console.error(error));

📌 Output after 2 seconds:


javascript

✅ Promise resolved successfully!

🔹 How to Implement Promises in JavaScript?


You can implement Promises by using the Promise constructor, which takes a callback function with
two parameters: resolve and reject .

1️⃣ Basic Promise Implementation


js

function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let success = true;
if (success) {

199/411
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data.");
}
}, 2000);
});
}

fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));

📌 Output (after 2 sec):


nginx

Data fetched successfully!

🔹 When to Use Promises in Real Applications?


Promises are used whenever we deal with asynchronous tasks, such as: ✔ Fetching API data:
( fetch() returns a Promise).
✔ Reading/writing files (Node.js).
✔ Handling timeouts and intervals.
✔ Executing dependent async tasks in a sequence.
✔ Executing multiple async tasks in parallel.

🔹 Promise.all()
Promise.all() takes multiple promises and waits for all of them to resolve (or rejects if any one
fails).

Example:
js

const p1 = new Promise(resolve => setTimeout(() => resolve("🍕 Pizza Ready"), 2000));
const p2 = new Promise(resolve => setTimeout(() => resolve("🍔 Burger Ready"), 3000));
const p3 = new Promise(resolve => setTimeout(() => resolve("🍟 Fries Ready"), 1000));

200/411
Promise.all([p1, p2, p3])
.then(results => console.log("All food ready:", results))
.catch(error => console.error("Error:", error));

📌 Output (after 3 seconds):


less

All food ready: [" 🍕 Pizza Ready", "🍔 Burger Ready", "🍟 Fries Ready"]
🔹 Key points: ✔ If all promises resolve → returns an array of results.
❌ If any one promise fails → entire Promise.all() fails.

🔹 Promise.race()
Promise.race() waits for the first Promise to resolve or reject.

Example:
js

const fast = new Promise(resolve => setTimeout(() => resolve("🚀 Fast Response"), 1000));
const slow = new Promise(resolve => setTimeout(() => resolve("🐢 Slow Response"), 3000));

Promise.race([fast, slow])
.then(result => console.log("First to resolve:", result))
.catch(error => console.error("Error:", error));

📌 Output (after 1 second):


css

First to resolve: 🚀 Fast Response


🔹 Key points: ✔ Only the first resolved/rejected promise is returned.
✔ Used when we need the fastest response (e.g., multiple API sources).

🔹 Difference Between Promise.all() and Promise.race()

201/411
Feature Promise.all() Promise.race()

Waits for All promises to complete First promise to resolve/reject

If one fails? Entire promise fails Still returns the first resolved/rejected promise

Use case When all results are needed When only the fastest result matters

🚀 Let me know if you need more real-world examples! 😊


What is the purpose of async/ await? Compare it with Promises?
04:15
Q136. Explain the use of async and await keywords in JS?
03:04
Q137. Can we use async keyword without await keyword and vice
versa?
00:44
Q138. How do you handle errors in async/ await functions?

🔹 Purpose of async/await in JavaScript

The async/await syntax in JavaScript makes asynchronous code easier to read and write. It simplifies
working with Promises by allowing developers to write asynchronous code in a synchronous manner.

✅ Benefits of async/await :
✔ Improves code readability.
✔ Eliminates callback hell and .then() chains.
✔ Handles errors using try...catch (like synchronous code).

Example: Using Promises


js

function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve(" ✅ Data fetched!"), 2000);
});
}

fetchData()
.then(result => console.log(result))
.catch(error => console.error(error));

📌 Output (after 2 sec):

202/411
✅ Data fetched!
Same Code Using async/await
js

async function fetchDataAsync() {


try {
let result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}

fetchDataAsync();

✅ Same Output but cleaner and easier to read.

🔹 Comparison: async/await vs Promises

Feature async/await Promises ( .then() / .catch() )

Syntax Synchronous-like, easy to read Uses .then() chaining

Error Handling Uses try...catch Uses .catch()

Code Complexity Cleaner and readable Can lead to callback hell

Execution Flow Waits ( await ) before proceeding Uses .then() , doesn't pause execution

🔹 How to Use async and await in JavaScript?

✔ async makes a function return a Promise.


✔ await pauses execution until the Promise resolves.

Example: Fetching API Data


js

203/411
async function getData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}

getData();

📌 Output:
json

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

🔹 Can We Use async Without await and Vice Versa?

1️⃣ Using async Without await

✔ You can declare an async function without await , but it behaves just like a regular function
returning a Promise.

js

async function test() {


return "Hello!";
}

test().then(console.log); // ✅ Output: Hello!


✔ Since there's no await , it immediately returns a resolved Promise.

204/411
2️⃣ Using await Without async

❌ Not possible!
✔ await can only be used inside an async function.
✔ Using it outside throws a SyntaxError.

js

// ❌ ERROR: "await is only valid in async functions"


let result = await fetch("https://jsonplaceholder.typicode.com/todos/1");

🔹 How to Handle Errors in async/await ?

The best way to handle errors in async/await is by using try...catch .

Example: Handling Errors in async/await


js

async function fetchData() {


try {
let response = await fetch("https://invalid-url.com");
let data = await response.json();
console.log(data);
} catch (error) {
console.error(" ❌ Error:", error.message);
}
}

fetchData();

📌 Output:
vbnet

❌ Error: Failed to fetch


Alternative: Using .catch()
js

async function fetchData() {


let response = await fetch("https://invalid-url.com");

205/411
return response.json();
}

fetchData()
.then(data => console.log(data))
.catch(error => console.error(" ❌ Error:", error.message));
✔ If an error occurs, it gets caught in .catch() .

🔹 Key Takeaways
✔ async makes a function return a Promise.
✔ await pauses execution until the Promise resolves.
✔ Easier to read compared to .then() chaining.
✔ Errors are handled using try...catch or .catch() .

🚀 Need more examples? Let me know! 😊


What is a window object?
01:01
Q140. What are Browser APIs in JS?
01:52
Q141. What is Web Storage, and its use? How many types of web
storage are there?
02:05
Q142. What is Local Storage? How to store, retrieve and remove
data from it?
02:21
Q143. What is Session Storage? How to store, retrieve and remove
data from it?
01:49
Q144. What is the difference between LocalStorage and
SessionStorage?
02:36
Q145. How much data can be stored in localStorage and
sessionStorage?
00:34
Q146. What are cookies? How do you create and read cookies?
01:49
Q147. What is the difference between cookies and web storage?
01:23
Q148. When to use cookies and when to use web storage?

206/411
🔹 Window Object in JavaScript
The window object is the global object in the browser that represents the browser window or tab.
✔ It provides methods and properties to interact with the browser.

Example: Accessing Window Properties


js

console.log(window.innerWidth); // ✅ Gets window width


console.log(window.innerHeight); // ✅ Gets window height

Common Methods in window


Method Description

window.alert() Shows an alert box.

window.confirm() Shows a confirmation dialog.

window.prompt() Shows an input dialog.

window.open() Opens a new browser tab/window.

window.setTimeout() Executes a function after a delay.

window.setInterval() Executes a function at regular intervals.

🔹 What are Browser APIs in JavaScript?


✔ Browser APIs are built-in JavaScript libraries that allow developers to interact with the browser.

Common Browser APIs


API Purpose

DOM API Manipulates HTML elements.

Geolocation API Gets user's location.

Fetch API Makes HTTP requests.

Web Storage API Stores data in the browser.

Canvas API Draws graphics on the screen.

Notifications API Shows system notifications.

Example: Using Fetch API


js

207/411
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(data => console.log(data));

🔹 What is Web Storage?


✔ Web Storage API allows storing key-value data in the browser.
✔ Two types of Web Storage:

localStorage → Stores data permanently.

sessionStorage → Stores data temporarily (clears when tab is closed).

🔹 Local Storage
Stores data permanently (until deleted manually or by code).

Example: Storing, Retrieving, and Removing Data

js

// Store data
localStorage.setItem("username", "Merin");

// Retrieve data
console.log(localStorage.getItem("username")); // ✅ Output: "Merin"
// Remove data
localStorage.removeItem("username");

// Clear all stored data


localStorage.clear();

🔹 Session Storage
Stores data temporarily (clears when the tab is closed).

208/411
Example: Storing, Retrieving, and Removing Data
js

// Store data
sessionStorage.setItem("sessionKey", "SessionData");

// Retrieve data
console.log(sessionStorage.getItem("sessionKey")); // ✅ Output: "SessionData"
// Remove data
sessionStorage.removeItem("sessionKey");

// Clear session storage


sessionStorage.clear();

🔹 Difference: localStorage vs sessionStorage

Feature localStorage sessionStorage

Data Persistence Permanent Cleared when tab closes

Storage Limit 5MB 5MB

Accessibility Accessible across all tabs/windows of the same origin Accessible only within the same tab

Use Case Storing user preferences, themes, tokens Temporary session data

🔹 Storage Limit of LocalStorage and SessionStorage


✔ Both localStorage and sessionStorage can store up to 5MB of data per domain.
✔ Exceeding the limit will result in a QuotaExceededError.

🔹 What are Cookies?


✔ Cookies are small data files stored in the browser, used for storing user information.
✔ They have an expiration date and are sent with every HTTP request.

209/411
Example: Creating and Reading Cookies
js

// Create a cookie (expires in 7 days)


document.cookie = "username=Merin; expires=" + new Date(2025, 0, 1).toUTCString();

// Read cookies
console.log(document.cookie);

🔹 Difference: Cookies vs Web Storage


Feature Cookies Web Storage ( localStorage & sessionStorage )

Size Limit ~4KB 5MB

Expiration Manually set localStorage (Never) / sessionStorage (Tab close)

Sent with Requests? ✅ Yes, sent with HTTP requests ❌ No


Use Case Authentication, tracking users Storing app data, preferences

🔹 When to Use Cookies vs Web Storage?


✔ Use Cookies: When data must be sent to the server (e.g., authentication tokens).
✔ Use Web Storage: When storing client-side data that doesn't need to be sent with each request.

🚀 Need more examples? Let me know! 😊


What is eval() function in JS?
00:49
Q162. What is XSS (Cross-Site Scripting) attack?
01:01
Q163. What is SQL Injection attack?
00:52
Q164. What are some best practices for security in JS?
01:19

210/411
Q165. What are the best practices for improving performance in
JS?

🔹 eval() Function in JavaScript

✔ The eval() function executes a string as JavaScript code.


✔ It is dangerous because it can execute malicious code and should be avoided.

Example: Using eval()


js

let x = 10;
let y = 20;
console.log(eval("x + y")); // ✅ Output: 30
🚨 Why eval() is Dangerous? ✔ If user input is executed using eval() , it can lead to security
vulnerabilities like XSS attacks.
✔ Better Alternative: Use JSON.parse() or Function() instead of eval() .

🔹 What is XSS (Cross-Site Scripting) Attack?


✔ XSS (Cross-Site Scripting) is a security vulnerability where attackers inject malicious JavaScript into
a website.
✔ The script can steal data, redirect users, or perform actions on behalf of users.

Example: XSS Attack via innerHTML

js

const userInput = "<script>alert('Hacked!');</script>";


document.getElementById("output").innerHTML = userInput; // 🚨 Executes malicious script!
Preventing XSS:
✔ Escape user input using textContent

js

document.getElementById("output").textContent = userInput;

✔ Use security libraries like DOMPurify.


✔ Avoid eval() and innerHTML when handling user input.

211/411
🔹 What is SQL Injection Attack?
✔ SQL Injection is an attack where malicious SQL queries are injected into an application’s database
queries.
✔ If input is not sanitized, attackers can delete data, steal sensitive information, or modify the
database.

Example: Vulnerable Code


js

const userInput = "'; DROP TABLE users; --"; // 🚨 Malicious input


const query = "SELECT * FROM users WHERE name = '" + userInput + "';";

Preventing SQL Injection:


✔ Use parameterized queries:

js

db.query("SELECT * FROM users WHERE name = ?", [userInput]);

✔ Use ORMs (like Sequelize, Mongoose).


✔ Sanitize and validate user input before using it in database queries.

🔹 Best Practices for Security in JavaScript


✅ 1. Escape User Input: Prevents XSS & SQL Injection.
✅ 2. Use HTTPS: Encrypts data transfers.
✅ 3. Avoid eval() and innerHTML : Prevents code injection attacks.
✅ 4. Use Content Security Policy (CSP): Blocks unauthorized scripts.
✅ 5. Implement Authentication & Authorization: Use JWT, OAuth.
✅ 6. Keep Dependencies Updated: Fixes known vulnerabilities.
✅ 7. Validate & Sanitize Input: Prevents malicious data execution.
✅ 8. Use Secure Cookies: HttpOnly and Secure flags.

212/411
🔹 Best Practices for Improving Performance in JavaScript
⚡ 1. Use Efficient Loops: Avoid unnecessary iterations.
⚡ 2. Minimize DOM Manipulation: Batch updates instead of modifying elements frequently.
⚡ 3. Use & : Avoids unnecessary global scope usage.
let const
⚡ 4. Use async& for Asynchronous Code: Prevents blocking UI.
await
⚡ 5. Debounce & Throttle: Limits frequent function calls (e.g., for scroll events).
⚡ 6. Reduce Unused Variables & Functions: Avoids memory leaks.
⚡ 7. Optimize Images & Assets: Compress files for faster loading.
⚡ 8. Use Lazy Loading for Images & Data: Loads content only when needed.
⚡ 9. Use Caching (LocalStorage, IndexedDB, HTTP Caching): Reduces server load.
⚡ 10. Optimize JavaScript File Sizes: Minify & bundle JS files.

🚀 Want more details? Let me know! 😊


What are Modules in JS?
02:36
Q156. What is the role of export keyword?
00:51
Q157. What are the advantages of modules?
00:56
Q158. What is the difference between named exports and default
exports?
01:01
Q159. What is the difference between static and dynamic imports?
01:22
Q160. What are module bundlers?

🔹 What are Modules in JavaScript?


✔ Modules in JavaScript allow you to split your code into smaller, reusable pieces.
✔ They help improve code organization, maintainability, and scalability by enabling separation of
concerns.

Example of Module:
js

// math.js (Module)
export function add(a, b) {
return a + b;
}

213/411
// main.js
import { add } from './math.js';
console.log(add(5, 3)); // Output: 8

🔹 What is the Role of the export Keyword?

✔ The export keyword is used to export functions, objects, or values from a module so that they can
be imported and used in other modules.

Example:
js

// Exporting a function
export function greet(name) {
return `Hello, ${name}!`;
}

// Exporting a constant
export const PI = 3.14159;

🔹 What are the Advantages of Modules?


✔ 1. Code Reusability: Modules allow you to write reusable code, making it easy to use across different
projects.
✔ 2. Better Maintainability: Each module focuses on one task, making it easier to manage.
✔ 3. Namespacing: Prevents name conflicts by encapsulating variables and functions in a module.
✔ 4. Improved Debugging: Smaller, isolated units of code are easier to debug.
✔ 5. Dependency Management: Modules help manage dependencies by clearly defining what a
module needs and what it provides.

🔹 What is the Difference Between Named Exports and Default


Exports?

214/411
Named Exports
✔ You can export multiple variables or functions from a module with specific names.
✔ When importing, the exact name is required.

js

// Named Export
export const sum = (a, b) => a + b;
export function multiply(a, b) { return a * b; }

// Importing
import { sum, multiply } from './math.js';

Default Export
✔ You can export a single value as the default export.
✔ It can be imported with any name.

js

// Default Export
export default function subtract(a, b) { return a - b; }

// Importing
import sub from './math.js';

🔹 What is the Difference Between Static and Dynamic


Imports?
Static Imports
✔ Static imports are done at the top of the file and are compiled at build time.
✔ This is the standard import syntax.

js

import { sum } from './math.js'; // Static Import

Dynamic Imports
✔ Dynamic imports allow you to import modules dynamically during runtime, often used for lazy
loading or code splitting.

215/411
✔ This returns a Promise.

js

async function loadModule() {


const { sum } = await import('./math.js');
console.log(sum(2, 3));
}
loadModule(); // Dynamic Import

🔹 What are Module Bundlers?


✔ Module Bundlers are tools that combine multiple JavaScript files (modules) into a single file or a
few optimized files.
✔ They help with code splitting, optimization, and dependency management.

Popular Module Bundlers:


Webpack: One of the most popular bundlers, offering features like hot module replacement,
code splitting, and tree shaking.

Parcel: An easy-to-use bundler that requires no configuration.

Rollup: Focuses on ES module bundling and tree shaking.

Example:
bash

# Bundle JavaScript files with Webpack


webpack --config webpack.config.js

Let me know if you need more clarification! 😊


Q186. How to validate user input as they type in a form?
01:37
Q187. How to implement pagination for displaying large sets of
data?
02:05
Q188. How to implement drag-and-drop functionality for elements

216/411
on a web page?
01:29
Q189. Feature that allows users to search for specific items in a
large dataset?
01:26
Q190. Feature that allows users to perform live search suggestions
as they type?
01:37
Q191. How to implement a real-time chat application using JS?
03:03
Q192. Create an infinite scrolling using JS when a user reaches the
webpage ?
01:25
Q193. Implement toggle switch to change the theme(light/dark
mode) of a website?
01:26
Q194. How to use JS to dynamically update date in real time on
webpage?
01:25
Q195. Prevent a form from being submitted without required
fields being filled?

Here are explanations for each of your questions:

Q186. How to validate user input as they type in a form?


To validate user input as they type, you can use the input event and check the value of the input
field.

Example:

html

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


<p id="error-msg" style="color: red; display: none;">Username is required.</p>

<script>
const inputField = document.getElementById('username');
const errorMsg = document.getElementById('error-msg');

inputField.addEventListener('input', function() {
if (inputField.value.trim() === '') {
errorMsg.style.display = 'block';
} else {

217/411
errorMsg.style.display = 'none';
}
});
</script>

Q187. How to implement pagination for displaying large sets of data?


Pagination can be implemented by dividing the dataset into pages and displaying only one page at a
time. You can use JavaScript to calculate which data to show based on the current page.

Example:

html

<div id="data"></div>
<button id="prev">Previous</button>
<button id="next">Next</button>

<script>
let currentPage = 1;
const itemsPerPage = 5;
const data = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);

function renderPage() {
const startIndex = (currentPage - 1) * itemsPerPage;
const pageData = data.slice(startIndex, startIndex + itemsPerPage);
document.getElementById('data').innerHTML = pageData.join('<br>');
}

document.getElementById('next').addEventListener('click', () => {
if (currentPage * itemsPerPage < data.length) {
currentPage++;
renderPage();
}
});

document.getElementById('prev').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
renderPage();
}
});

218/411
renderPage();
</script>

Q188. How to implement drag-and-drop functionality for elements on a web


page?
The DragEvent API allows you to implement drag-and-drop functionality. Use the dragstart ,
dragover , and drop events.

Example:

html

<div id="drag" draggable="true" style="width: 100px; height: 100px; background-color:


lightblue;">Drag Me</div>
<div id="drop" style="width: 200px; height: 200px; border: 2px dashed #ccc;">Drop Here</div>

<script>
const dragElement = document.getElementById('drag');
const dropZone = document.getElementById('drop');

dragElement.addEventListener('dragstart', (e) => {


e.dataTransfer.setData('text', e.target.id);
});

dropZone.addEventListener('dragover', (e) => {


e.preventDefault();
});

dropZone.addEventListener('drop', (e) => {


e.preventDefault();
const data = e.dataTransfer.getData('text');
const draggedElement = document.getElementById(data);
dropZone.appendChild(draggedElement);
});
</script>

Q189. Feature that allows users to search for specific items in a large
dataset?

219/411
To implement a search feature, you can use an input field and filter the displayed data based on the
user's input.

Example:

html

<input type="text" id="search" placeholder="Search items...">


<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>

<script>
document.getElementById('search').addEventListener('input', function() {
const searchQuery = this.value.toLowerCase();
const items = document.querySelectorAll('#list li');

items.forEach(item => {
if (item.textContent.toLowerCase().includes(searchQuery)) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
});
</script>

Q190. Feature that allows users to perform live search suggestions as they
type?
For live search suggestions, you can display suggestions dynamically based on the user's input.

Example:

html

<input type="text" id="search" placeholder="Search...">


<ul id="suggestions"></ul>

<script>
const items = ['Apple', 'Banana', 'Cherry', 'Grape', 'Orange'];

220/411
document.getElementById('search').addEventListener('input', function() {
const query = this.value.toLowerCase();
const filteredItems = items.filter(item => item.toLowerCase().includes(query));

const suggestions = document.getElementById('suggestions');


suggestions.innerHTML = filteredItems.map(item => `<li>${item}</li>`).join('');
});
</script>

Q191. How to implement a real-time chat application using JS?


A real-time chat app can be built using WebSockets or libraries like Socket.IO.

Example using Socket.IO:

html

<!-- HTML -->


<input id="message" type="text" placeholder="Type a message">
<button id="send">Send</button>
<div id="chat"></div>

<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
const socket = io('http://localhost:3000');

document.getElementById('send').addEventListener('click', () => {
const message = document.getElementById('message').value;
socket.emit('chatMessage', message);
});

socket.on('chatMessage', message => {


const chat = document.getElementById('chat');
chat.innerHTML += `<p>${message}</p>`;
});
</script>

Q192. Create an infinite scrolling using JS when a user reaches the webpage?

221/411
To implement infinite scrolling, you can use the scroll event and check if the user has scrolled to the
bottom of the page.

Example:

html

<div id="content"></div>

<script>
let page = 1;

function loadContent() {
for (let i = 1; i <= 10; i++) {
const item = document.createElement('div');
item.textContent = `Item ${((page - 1) * 10) + i}`;
document.getElementById('content').appendChild(item);
}
}

window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight) {
page++;
loadContent();
}
});

loadContent(); // Load initial content


</script>

Q193. Implement toggle switch to change the theme (light/dark mode) of a


website?
A toggle switch for changing themes can be done by toggling a class (like dark-theme ) on the body or
container.

Example:

html

<button id="themeToggle">Toggle Theme</button>

<script>
const themeToggle = document.getElementById('themeToggle');

222/411
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-theme');
});
</script>

<style>
body {
background-color: white;
color: black;
}
.dark-theme {
background-color: black;
color: white;
}
</style>

Q194. How to use JS to dynamically update date in real-time on webpage?


You can use the setInterval() method to update the date and time in real-time.

Example:

html

<div id="date-time"></div>

<script>
function updateDateTime() {
const date = new Date();
document.getElementById('date-time').textContent = date.toLocaleString();
}
setInterval(updateDateTime, 1000);
updateDateTime(); // Initial update
</script>

Q195. Prevent a form from being submitted without required fields being
filled?
You can use the required attribute on form fields or validate it using JavaScript before submission.

223/411
Example:

html

<form id="myForm">
<input type="text" id="username" required placeholder="Enter username">
<button type="submit">Submit</button>
</form>

<script>
const form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
const username = document.getElementById('username');
if (!username.value.trim()) {
event.preventDefault();
alert('Username is required!');
}
});
</script>

Let me know if you need further explanation or examples! 😊


Q196. Write a function that returns the reverse of a string?
02:04
Q197. Write a function that returns the longest word in the
sentence?
02:13
Q198. Function that checks whether a given string is a palindrome
or not?
01:23
Q199. Write a function to remove duplicate elements from an
array?
03:42
Q200. Write a function that checks whether two strings are
anagrams or not?
01:58
Q201. Write a function that returns the number of vowels in a
string?
01:50
Q202. Write a function to find the largest number in an array?
01:47
Q203. Write a function to check if a given number is prime or not?

224/411
02:21
Q204. Write a function to calculate the factorial of a number?
01:38
Q205. Write a program to remove all whitespace characters from a
string?
01:46
Q206. Write a function to find the sum of all elements in an array?
00:43
Q207. Write a function to find the average of an array of numbers?
00:33
Q208. Write a function to sort an array of numbers in ascending
order?
03:14
Q209. Write a function to check if an array is sorted in ascending
order or not?
01:41
Q210. Write a function to merge two arrays into a single sorted
array?
01:13
Q211. Write a function to remove a specific element from an array?
01:49
Q212. Write a function to find the second largest element in an
array?
01:19
Q213. Write a function to reverse the order of words in a given
sentence?
00:49
Q214. Function to find the longest common prefix among an array
of strings?
03:32
Q215. Write a function to find the intersection of two arrays?
01:32
Q216. Write a function to calculate the Fibonacci sequence up to a
given number?

Here are the functions for each of your requests:

Q196. Write a function that returns the reverse of a string?


javascript

function reverseString(str) {
return str.split('').reverse().join('');
}

225/411
console.log(reverseString("hello")); // Output: "olleh"

Q197. Write a function that returns the longest word in the sentence?
javascript

function longestWord(sentence) {
const words = sentence.split(' ');
let longest = '';
for (let word of words) {
if (word.length > longest.length) {
longest = word;
}
}
return longest;
}

console.log(longestWord("This is a simple sentence")); // Output: "sentence"

Q198. Function that checks whether a given string is a palindrome or not?


javascript

function isPalindrome(str) {
const cleanedStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleanedStr === cleanedStr.split('').reverse().join('');
}

console.log(isPalindrome("A man a plan a canal Panama")); // Output: true

Q199. Write a function to remove duplicate elements from an array?


javascript

226/411
function removeDuplicates(arr) {
return [...new Set(arr)];
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]

Q200. Write a function that checks whether two strings are anagrams or not?
javascript

function areAnagrams(str1, str2) {


const normalize = (str) => str.split('').sort().join('');
return normalize(str1) === normalize(str2);
}

console.log(areAnagrams("listen", "silent")); // Output: true

Q201. Write a function that returns the number of vowels in a string?


javascript

function countVowels(str) {
const vowels = 'aeiouAEIOU';
return str.split('').filter(char => vowels.includes(char)).length;
}

console.log(countVowels("hello world")); // Output: 3

Q202. Write a function to find the largest number in an array?


javascript

function largestNumber(arr) {
return Math.max(...arr);
}

227/411
console.log(largestNumber([3, 5, 7, 2, 8])); // Output: 8

Q203. Write a function to check if a given number is prime or not?


javascript

function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}

console.log(isPrime(7)); // Output: true

Q204. Write a function to calculate the factorial of a number?

javascript

function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}

console.log(factorial(5)); // Output: 120

Q205. Write a program to remove all whitespace characters from a string?


javascript

function removeWhitespace(str) {
return str.replace(/\s+/g, '');
}

228/411
console.log(removeWhitespace("Hello World ")); // Output: "HelloWorld"

Q206. Write a function to find the sum of all elements in an array?


javascript

function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}

console.log(sumArray([1, 2, 3, 4])); // Output: 10

Q207. Write a function to find the average of an array of numbers?


javascript

function averageArray(arr) {
return arr.reduce((sum, num) => sum + num, 0) / arr.length;
}

console.log(averageArray([1, 2, 3, 4])); // Output: 2.5

Q208. Write a function to sort an array of numbers in ascending order?


javascript

function sortArray(arr) {
return arr.sort((a, b) => a - b);
}

console.log(sortArray([3, 1, 4, 1, 5, 9])); // Output: [1, 1, 3, 4, 5, 9]

229/411
Q209. Write a function to check if an array is sorted in ascending order or
not?
javascript

function isSorted(arr) {
return arr.every((val, i) => i === 0 || val >= arr[i - 1]);
}

console.log(isSorted([1, 2, 3, 4])); // Output: true


console.log(isSorted([1, 3, 2, 4])); // Output: false

Q210. Write a function to merge two arrays into a single sorted array?

javascript

function mergeArrays(arr1, arr2) {


return arr1.concat(arr2).sort((a, b) => a - b);
}

console.log(mergeArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6]

Q211. Write a function to remove a specific element from an array?


javascript

function removeElement(arr, element) {


return arr.filter(item => item !== element);
}

console.log(removeElement([1, 2, 3, 4], 3)); // Output: [1, 2, 4]

Q212. Write a function to find the second largest element in an array?


javascript

230/411
function secondLargest(arr) {
let uniqueArr = [...new Set(arr)].sort((a, b) => b - a);
return uniqueArr[1];
}

console.log(secondLargest([1, 2, 3, 4])); // Output: 3

Q213. Write a function to reverse the order of words in a given sentence?


javascript

function reverseWords(sentence) {
return sentence.split(' ').reverse().join(' ');
}

console.log(reverseWords("Hello World")); // Output: "World Hello"

Q214. Function to find the longest common prefix among an array of strings?

javascript

function longestCommonPrefix(arr) {
if (arr.length === 0) return "";
let prefix = arr[0];
for (let i = 1; i < arr.length; i++) {
while (arr[i].indexOf(prefix) !== 0) {
prefix = prefix.slice(0, -1);
}
}
return prefix;
}

console.log(longestCommonPrefix(["flower", "flow", "flight"])); // Output: "fl"

231/411
Q215. Write a function to find the intersection of two arrays?
javascript

function intersection(arr1, arr2) {


return arr1.filter(item => arr2.includes(item));
}

console.log(intersection([1, 2, 3], [2, 3, 4])); // Output: [2, 3]

Q216. Write a function to calculate the Fibonacci sequence up to a given


number?
javascript

function fibonacci(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib;
}

console.log(fibonacci(10)); // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Let me know if you need further assistance with any of the above functions! 😊
Q. What is HTML? Differences between HTML & HTML5?
Advantages of HTML5?
04:47
Q. What is the difference between HTML and XHTML?
02:33
Q. What is the role of DOCTYPE in HTML?
01:25
Q. What if you remove <!DOCTYPE html> from your HTML?
00:33
Q. Difference between Head & Body in HTML? Where to place JS
link reference?
02:15

232/411
Q. What is Title Tag in HTML? What are the 4 advantages of Title
tag?
01:55
Q. What are Meta Tags? What are the 5 types of meta tags?

Here are the explanations for your HTML-related questions:

What is HTML? Differences between HTML & HTML5? Advantages of HTML5?


HTML (Hypertext Markup Language) is the standard language used to create and design
webpages. It defines the structure of web pages using elements or tags like <html> , <head> ,
<body> , and more.

Differences between HTML & HTML5:

1. Doctype Declaration: HTML5 uses <!DOCTYPE html> , while older versions like HTML4 use
<!DOCTYPE HTML PUBLIC...> .

2. New Elements: HTML5 introduces new semantic elements like <header> , <footer> ,
<section> , <article> , and <nav> , which help structure the content better.

3. Multimedia Support: HTML5 supports native video and audio elements ( <video> and
<audio> ) without needing plugins.

4. Forms: HTML5 provides new input types such as email , date , range , and more.

5. APIs: HTML5 comes with integrated APIs like Geolocation, Web Storage, and WebSockets.

Advantages of HTML5:

1. Improved support for multimedia without the need for plugins.

2. Native support for web applications and offline capabilities.

3. Better semantic structure of web content.

4. Improved form controls and input fields.

5. Support for local storage and enhanced data handling.

What is the difference between HTML and XHTML?


HTML (Hypertext Markup Language) is a standard markup language that uses a flexible syntax,
allowing certain elements and attributes to be omitted.

XHTML (Extensible HTML) is a stricter version of HTML based on XML. Some key differences:

233/411
1. XHTML requires all tags to be properly closed (e.g., <img src="image.jpg" /> ), while HTML
allows self-closing tags to be optional.

2. XHTML elements must be written in lowercase (e.g., <body> ), while HTML is case-insensitive.

3. XHTML requires the use of the <!DOCTYPE> declaration.

What is the role of DOCTYPE in HTML?


The DOCTYPE declaration specifies which version of HTML the document is written in. It helps the
browser to render the page correctly according to the version's rules. For example, <!DOCTYPE
html> is used for HTML5.

What if you remove <!DOCTYPE html> from your HTML?


If the <!DOCTYPE html> is removed, the browser might render the page in "quirks mode," which
can cause issues with layout and styling. In quirks mode, the browser follows older, less predictable
rules for rendering HTML.

Difference between Head & Body in HTML? Where to place JS link reference?
Head ( <head> ):

Contains metadata about the document, like title, meta tags, link to stylesheets, and other
resources.

Doesn't display content on the page directly.

Body ( <body> ):

Contains the actual content that appears on the page, such as text, images, and other
elements.

Where to place JS link reference?

Ideally, JavaScript should be placed at the end of the <body> tag or inside the <head> tag
with the async or defer attribute.

Placing JavaScript at the end of the body helps avoid blocking the rendering of the page
content.

234/411
What is Title Tag in HTML? What are the 4 advantages of Title tag?
The <title> tag defines the title of the webpage, which appears on the browser's title bar or tab.

Advantages of the Title tag:

1. Improves SEO (Search Engine Optimization) by providing a clear description of the page.

2. Helps users quickly identify the page in browser tabs or search results.

3. Provides a description of the page when shared on social media platforms.

4. Essential for accessibility and improving user experience.

What are Meta Tags? What are the 5 types of meta tags?
Meta tags provide metadata about the HTML document, like description, keywords, and author,
which is used by search engines and browsers.

5 types of meta tags:

1. Meta Description: Provides a brief summary of the page content for search engines.

html

<meta name="description" content="This is a webpage about HTML basics">

2. Meta Keywords: Contains keywords related to the page for SEO purposes.

html

<meta name="keywords" content="HTML, CSS, JavaScript, Web Development">

3. Meta Author: Specifies the author of the page content.

html

<meta name="author" content="John Doe">

4. Meta Charset: Defines the character encoding for the page (e.g., UTF-8).

html

<meta charset="UTF-8">

5. Meta Robots: Directs search engine crawlers on how to index or follow links on the page.

235/411
html

<meta name="robots" content="noindex, nofollow">

Let me know if you'd like more detailed explanations or further examples!

Q. What are HTML elements? What is the difference between


Element & Tag?
02:07
Q. What are the roles and uses of the <div> element in HTML?
02:07
Q. What is the difference between <div> and <span> element?
01:00
Q. What is the role of <p>, <a>, <br>, <hr>, <em>, <img>, <input> &
<button> ele
02:50
Q. What is the role of header, main, section, footer & address
elements in HTML?
02:00
Q. What is the role of Heading tags in HTML? How does it impact
SEO?
02:56
Q. What is the difference between <section> & <article> elements?

Here are the explanations for your HTML elements-related questions:

What are HTML elements? What is the difference between Element & Tag?
HTML Elements: An HTML element is a combination of an opening tag, content, and a closing tag.
For example:

html

<p>This is a paragraph.</p>

Here, <p> is the opening tag, This is a paragraph. is the content, and </p> is the closing tag.
The entire structure is considered an HTML element.

Difference between Element & Tag:

236/411
A Tag is the markup that denotes the beginning or end of an HTML element (e.g., <p> is an
opening tag, </p> is a closing tag).

An Element refers to the complete combination of the opening tag, content, and closing tag
(e.g., <p>This is a paragraph.</p> is a paragraph element).

What are the roles and uses of the <div> element in HTML?
The <div> element is a block-level container used to group together other HTML elements. It is
commonly used for layout purposes, as it allows you to structure content into sections without
adding any semantic meaning to it.

Uses of <div> :

1. Grouping content for styling purposes (via CSS).

2. Creating layout containers (e.g., for grids or flexible boxes).

3. Used with JavaScript for DOM manipulation and event handling.

html

<div class="container">
<p>Content goes here.</p>
</div>

What is the difference between <div> and <span> element?


<div> is a block-level element, which means it takes up the full width available and starts on a
new line. It is used for grouping larger content blocks.

<span> is an inline element, which means it only takes up as much width as its content and does
not start on a new line. It is used for styling smaller sections of text or inline content.

Example:

html

<div>Block-level content</div>
<span>Inline content</span>

237/411
What is the role of <p> , <a> , <br> , <hr> , <em> , <img> , <input> , & <button>
elements in HTML?
<p> : Defines a paragraph. Used to structure text into separate blocks.

html

<p>This is a paragraph.</p>

<a> : Defines a hyperlink. Used to create links to other webpages or resources.

html

<a href="https://www.example.com">Visit Example</a>

<br> : Defines a line break. Used to insert a single line break in text.

html

Hello<br>World!

<hr> : Defines a horizontal rule. Used to create a thematic break in a page (usually displayed as a
line).

html

<hr>

<em> : Defines emphasized text. It is typically displayed in italics and used for stressing words.

html

<em>Important</em> text.

<img> : Defines an image. It embeds images into a webpage.

html

<img src="image.jpg" alt="Image description">

<input> : Defines an input field in forms, where the user can enter data.

html

<input type="text" placeholder="Enter text">

<button> : Defines a clickable button. Typically used to trigger actions when clicked.

238/411
html

<button>Click Me</button>

What is the role of <header> , <main> , <section> , <footer> , and <address>


elements in HTML?
<header> : Represents the header section of a document or a section. Typically contains
navigational elements, logos, or introductory content.

html

<header>
<h1>Website Title</h1>
</header>

<main> : Represents the main content of the document. It is used to highlight the primary content
of the page.

html

<main>
<p>Main content goes here.</p>
</main>

<section> : Represents a section of content, often with a specific theme or purpose, like a chapter
or a group of related content.

html

<section>
<h2>About Us</h2>
<p>Content here...</p>
</section>

<footer> : Represents the footer section of a document or a section, typically containing metadata
or copyright information.

html

<footer>
<p>&copy; 2025 Your Company</p>
</footer>

239/411
<address> : Represents contact information for the author or owner of a document or section.

html

<address>
<p>Contact us at: [email protected]</p>
</address>

What is the role of Heading tags in HTML? How does it impact SEO?
Heading tags ( <h1> , <h2> , <h3> , etc.) define headings and subheadings in a webpage, used to
organize content hierarchically.

Impact on SEO:

1. Organizes Content: Helps search engines understand the structure and context of the
content.

2. Improves Accessibility: Allows screen readers and assistive technologies to identify and
navigate the content more easily.

3. Boosts Keyword Relevance: Headings (especially <h1> ) often include important keywords
that impact ranking on search engines.

It is recommended to use headings in a logical hierarchy (e.g., <h1> for the main title, <h2> for
subheadings).

What is the difference between <section> & <article> elements?


<section> : Represents a section of content within a document, typically with a thematic grouping,
like a chapter or grouping of related content. It doesn't necessarily have to be self-contained.

html

<section>
<h2>Introduction</h2>
<p>Content about the introduction.</p>
</section>

<article> : Represents a self-contained piece of content, such as a blog post, news story, or user
comment, that can be distributed or reused independently.

240/411
html

<article>
<h2>Blog Post Title</h2>
<p>Content of the blog post...</p>
</article>

These explanations should clarify the different roles and uses of HTML elements. Let me know if you'd
like further details!

Q. What are Root, Parent, Child & Nested elements?


01:44
Q. What are Empty Elements?
01:23
Q. What are Semantic Elements in HTML? Is div a semantic
element?
01:45
Q. Can HTML tags be written in Uppercase?
00:49
Q. What are the 3 differences between Block-Level and Inline
Elements?
01:33
Q. List all Block-Level & Inline Elements in HTML.

Here are the explanations for your HTML-related questions:

What are Root, Parent, Child & Nested elements?


Root Element: The top-level element in an HTML document, typically the <html> tag. It is the
starting point for the document's structure.

html

<html>
<head></head>
<body></body>
</html>

Parent Element: An element that contains one or more other elements. For example, in this
snippet, <div> is the parent of <p> :

241/411
html

<div>
<p>This is a paragraph.</p>
</div>

Child Element: An element that is inside another element. In the example above, <p> is the child
of <div> .

Nested Elements: Elements that are placed inside other elements. Nested elements can be
parents or children depending on their position in the structure.

html

<div>
<section>
<p>Nested content.</p>
</section>
</div>

What are Empty Elements?


Empty Elements (also known as self-closing or void elements) are elements that do not have any
content or closing tag. These elements are typically used to insert non-content items like images,
line breaks, or horizontal rules.

Examples:

<img> : Used to insert images.

<br> : Adds a line break.

<hr> : Adds a horizontal rule.

html

<img src="image.jpg" alt="image description">


<br>
<hr>

What are Semantic Elements in HTML? Is div a semantic element?

242/411
Semantic Elements: These elements clearly describe their meaning in both the browser and
developer's context. They improve accessibility, SEO, and code readability.

Examples of Semantic Elements:

<header> , <article> , <section> , <footer> , <nav> , <aside>

These elements provide meaning about the structure of the content. For example, <article> is
for a self-contained piece of content like a blog post, and <header> defines the header section.

Is <div> a Semantic Element?

No, the <div> element is not a semantic element. It is a non-semantic container that has no
meaning on its own but is used for grouping content for styling or scripting purposes.

html

<div class="container">
<p>This is a paragraph inside a div.</p>
</div>

Can HTML tags be written in Uppercase?


Yes, HTML tags can be written in uppercase, although it is not common practice. HTML is case-
insensitive, so both <div> and <DIV> are valid.

Example:

html

<DIV>
<P>Hello, World!</P>
</DIV>

However, it is recommended to use lowercase for tags for consistency and readability, as per
modern HTML standards.

What are the 3 differences between Block-Level and Inline Elements?


1. Display Behavior:

Block-Level Elements: Occupy the full width of their parent container and start on a new line
(e.g., <div> , <p> ).

243/411
Inline Elements: Only take up as much width as necessary and do not start on a new line (e.g.,
<span> , <a> ).

2. Height and Width:

Block-Level Elements: Can have defined width and height.

Inline Elements: Do not accept width and height properties (they are determined by their
content).

3. Structure:

Block-Level Elements: Can contain other block-level and inline elements.

Inline Elements: Can only contain other inline elements.

List all Block-Level & Inline Elements in HTML.


Block-Level Elements:

<div>

<p>

<h1> , <h2> , <h3> , <h4> , <h5> , <h6>

<section>

<article>

<header>

<footer>

<nav>

<aside>

<form>

<ul> , <ol> , <li>

<table> , <tr> , <th> , <td>

<blockquote>

<pre>

<hr>

Inline Elements:

<span>

<a>

244/411
<strong>

<em>

<img>

<b> , <i>

<u>

<abbr>

<code>

<sub> , <sup>

<q>

<br> (although technically a self-closing tag, it behaves as inline in the document flow)

These are the explanations for the HTML-related concepts you're asking about! Let me know if you'd
like any more details.

What are HTML Attributes? What are the Types of HTML attributes?
01:49
Q. What are the Id, Style & Class attributes of an element? When to
use what?
02:36
Q. What will happen if two elements have same ids?
01:21
Q. Multiple Classes for single element? Style precedence?
01:16
Q. What are Data Attributes in HTML?

Here are the answers to your HTML attribute-related questions:

What are HTML Attributes? What are the Types of HTML attributes?
HTML Attributes: Attributes in HTML provide additional information about an element, such as its
behavior, style, or properties. They are written inside the opening tag of an element and are made
up of a name and a value pair.

Example:

html

245/411
<a href="https://example.com" target="_blank">Visit Example</a>

Types of HTML Attributes:

1. Global Attributes: These can be used with any HTML element (e.g., id , class , style ,
title ).

2. Event Attributes: These are used to handle events (e.g., onclick , onload , onmouseover ).

3. Form-related Attributes: These are used in form elements (e.g., action , method , name ,
value ).

4. Image-related Attributes: These are used with <img> elements (e.g., src , alt , width ,
height ).

5. Link-related Attributes: These are used with links (e.g., href , rel , type ).

What are the Id, Style & Class attributes of an element? When to use what?
id Attribute:

Purpose: Assigns a unique identifier to an element. Each id should be unique within the
document.

When to use: Use it when you need to target an element uniquely with JavaScript or CSS.

Example:

html

<div id="main-content">Content here</div>

style Attribute:

Purpose: Used to apply inline CSS styles directly to an element.

When to use: Use it when you want to apply styles to an element temporarily, but it’s better to
use an external CSS file for maintainability.

Example:

html

<div style="color: blue; background-color: yellow;">Styled Content</div>

class Attribute:

246/411
Purpose: Used to define one or more classes that an element belongs to. Classes can be
shared across multiple elements.

When to use: Use it when you want to group elements and apply the same style or behavior
across multiple elements.

Example:

html

<div class="highlight">Important Content</div>

What will happen if two elements have the same ids?


IDs must be unique within the HTML document. If two elements share the same id , it can lead to
unpredictable behavior, especially in JavaScript and CSS. JavaScript functions like
getElementById() will return only the first element with that ID, and CSS selectors may also apply
styles incorrectly.

Example of potential issue:

html

<div id="header">Header 1</div>


<div id="header">Header 2</div>

In this case, both <div> elements have the same id of "header," which is not recommended. Use
classes for multiple elements instead of id .

Multiple Classes for a Single Element? Style Precedence?


Multiple Classes: An element can have multiple classes, separated by spaces. This is useful when
you want to apply multiple styles or behaviors to a single element.

Example:

html

<div class="box large red">Content</div>

247/411
Style Precedence: When multiple CSS rules apply to the same element, the specificity of the
selector determines which style takes precedence:

1. Inline styles (highest precedence).

2. IDs.

3. Classes, pseudo-classes, and attributes.

4. Elements (lowest precedence).

If two classes apply conflicting styles, the last defined class in the list will take precedence.

Example:

html

<style>
.red { color: red; }
.blue { color: blue; }
</style>
<div class="red blue">This will be blue</div>

What are Data Attributes in HTML?


Data Attributes: These are custom attributes that allow you to store extra information on an HTML
element. They start with data- and are used to store non-visible data that can be accessed by
JavaScript.

Example:

html

<div data-user-id="123" data-user-role="admin">User Info</div>

In JavaScript, you can access these data attributes via the dataset property:

javascript

const userDiv = document.querySelector('div');


console.log(userDiv.dataset.userId); // Output: 123
console.log(userDiv.dataset.userRole); // Output: admin

Use: Data attributes are commonly used for storing additional information that you need to access
via JavaScript without affecting the presentation of the element.

248/411
Let me know if you'd like further clarification on any of these topics!

Q. What are the 5 Types of Links in HTML?


02:33
Q. What is the difference between Absolute and Relative URLs?
02:57
Q. What is the purpose of the <nav> element in HTML?
01:42
Q. What is a Fragment Identifier in a URL?
01:13
Q. What is the purpose of the <base> element in HTML.?
01:13
Q. How do you add an external stylesheet in your HTML?
00:44
Q. How do you open a link in a new tab?
01:10
Q. How do you create an Email Link?

Here are the answers to your questions:

What are the 5 Types of Links in HTML?


1. Internal Links: These links point to another page within the same website. They are relative URLs
and are used to navigate between different pages of a website.

Example:

html

<a href="about.html">About Us</a>

2. External Links: These links point to a different website or domain. They use full URLs (absolute
URLs).

Example:

html

<a href="https://www.example.com">Visit Example</a>

3. Anchor Links (Fragment Links): These are used to navigate to a specific section within the same
page. It uses the id attribute to target a specific element.

249/411
Example:

html

<a href="#section1">Go to Section 1</a>

4. Mailto Links: These are used to create links that open the user's email client and automatically
populate the "To" field with a specified email address.

Example:

html

<a href="mailto:[email protected]">Email Us</a>

5. Telephone Links: These links allow users to dial a phone number directly from the web page
(mostly used on mobile devices).

Example:

html

<a href="tel:+1234567890">Call Us</a>

What is the difference between Absolute and Relative URLs?


Absolute URL: An absolute URL provides the full path to a resource, including the protocol
( http:// or https:// ), domain name, and sometimes the file path. It is used to link to an
external resource or when the full URL is necessary.

Example:

html

<a href="https://www.example.com/contact.html">Contact</a>

Relative URL: A relative URL provides the path to a resource relative to the current page's location.
It does not include the domain name or protocol, making it shorter and more flexible for internal
navigation within the same website.

Example:

html

<a href="about.html">About</a>

250/411
What is the purpose of the <nav> element in HTML?
The <nav> element is used to define a navigation section in an HTML document. It typically
contains a list of links used for navigation within the website or application. It helps search engines
and screen readers understand that the enclosed links are for navigation purposes.

Example:

html

<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>

What is a Fragment Identifier in a URL?


A Fragment Identifier is used in URLs to refer to a specific part or section of a document. It begins
with a # symbol and is followed by an ID of an element within the page. When the URL is visited,
the browser scrolls to the element with the corresponding ID.

Example:

html

<a href="page.html#section1">Go to Section 1</a>

Here, #section1 is the fragment identifier that points to the element with the id="section1" .

What is the purpose of the <base> element in HTML?


The <base> element is used to define the base URL for all relative URLs within a document. It
should be placed inside the <head> section of the HTML document. This helps in defining a
common reference point for all relative links, which is especially useful if the links on the page are
from different directories.

251/411
Example:

html

<head>
<base href="https://www.example.com/">
</head>
<body>
<a href="about.html">About Us</a> <!-- This will point to
https://www.example.com/about.html -->
</body>

How do you add an external stylesheet in your HTML?


You can add an external stylesheet to your HTML document using the <link> tag in the <head>
section.

Example:

html

<head>
<link rel="stylesheet" href="styles.css">
</head>

This will link the styles.css file to the HTML document, applying the styles defined in it.

How do you open a link in a new tab?


To open a link in a new tab, you can use the target="_blank" attribute in the <a> tag.

Example:

html

<a href="https://www.example.com" target="_blank">Visit Example</a>

This will open the link in a new browser tab.

252/411
How do you create an Email Link?
To create an email link, you use the mailto: protocol in the href attribute. When clicked, this link
will open the default email client with a new email draft.

Example:

html

<a href="mailto:[email protected]">Email Us</a>

You can also add a subject or body to the email:

Example with Subject:

html

<a href="mailto:[email protected]?subject=Feedback">Email Us</a>

Let me know if you need further clarification on any of these topics!

Q. What are the different Types of Lists in HTML?


02:19
Q. What is a Nested List in HTML?
00:52
Q. What are table, tr, th, td elements? What are table advantages &
disadvantage
02:20
Q. What is the colspan attribute in HTML?
01:12
Q. What is the best way to add a border to a table, column and
cell?

Here are the answers to your questions:

What are the different Types of Lists in HTML?


In HTML, there are three main types of lists:

1. Ordered List ( <ol> ): A list where the items are numbered or ordered. Each item in the list is
wrapped in an <li> tag.

253/411
Example:

html

<ol>
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
</ol>

2. Unordered List ( <ul> ): A list where the items are not numbered, and typically represented with
bullets. Each item in the list is wrapped in an <li> tag.

Example:

html

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

3. Definition List ( <dl> ): A list of terms and their definitions. Each term is wrapped in a <dt>
(definition term) tag, and each definition is wrapped in a <dd> (definition description) tag.

Example:

html

<dl>
<dt>HTML</dt>
<dd>A markup language for creating web pages.</dd>
<dt>CSS</dt>
<dd>A style sheet language for styling HTML elements.</dd>
</dl>

What is a Nested List in HTML?


A nested list is a list that contains another list inside one of its list items. Both ordered ( <ol> ) and
unordered ( <ul> ) lists can be nested.

Example:

html

254/411
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Sub-item 2.1</li>
<li>Sub-item 2.2</li>
</ul>
</li>
<li>Item 3</li>
</ul>

In this example, Item 2 contains another unordered list.

What are table, tr, th, td elements? What are the advantages & disadvantages
of tables?
1. <table> : Defines the table itself.

Example:

html

<table>
<!-- Table content here -->
</table>

2. <tr> : Defines a row in the table.

Example:

html

<tr>
<!-- Table row content -->
</tr>

3. <th> : Defines a header cell in a table, typically bold and centered. It is used within a <tr> to
specify column headings.

Example:

html

<th>Header 1</th>

255/411
4. <td> : Defines a data cell in a table. It is used to define regular table content within a row.

Example:

html

<td>Data 1</td>

Advantages of using tables:

Structured Data Representation: Tables are great for displaying structured data, such as rows and
columns, and are commonly used in financial, statistical, or tabular data.

Easy to Use: HTML tables provide an easy way to display data in a grid-like structure.

Disadvantages of using tables:

Accessibility Issues: Tables can be challenging for screen readers and assistive technologies,
especially if they are not marked up with proper <th> and <caption> elements.

Not Responsive by Default: Tables can be challenging to make responsive without additional CSS
or JavaScript, especially when the content is too wide for mobile devices.

What is the colspan attribute in HTML?


The colspan attribute in HTML is used in a <td> or <th> element to specify how many columns a cell
should span across. It allows a single cell to extend over multiple columns.

Example:

html

<table>
<tr>
<th colspan="2">Header spanning two columns</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>

In this example, the header will span across two columns.

256/411
What is the best way to add a border to a table, column, and cell?
The best way to add borders to tables, columns, and cells is by using CSS. You can specify borders
using the border property.

Adding a border to the entire table:

html

<table style="border: 2px solid black;">


<!-- Table content -->
</table>

Adding a border to individual cells:

html

<td style="border: 1px solid black;">Cell data</td>

Adding a border to columns (using :nth-child ):

While you can't directly add borders to columns in HTML, you can style all cells within a specific column
using CSS selectors like nth-child .

Example:

html

<style>
td:nth-child(1), th:nth-child(1) {
border-left: 2px solid black;
}
td:nth-child(2), th:nth-child(2) {
border-right: 2px solid black;
}
</style>

<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>

257/411
This method can be used to style borders for specific columns.

Let me know if you need further details!

Q. How to embed an Image in HTML? Why alt attribute is so


important?
02:00
Q. What are the difference between JPEG and PNG image formats?
01:22
Q. How to embed Video element in HTML? Why we need multiple
source elements?
02:18
Q. How to embed Audio element in HTML?
00:43
Q. What are the Autoplay & Loop attributes in multimedia
elements?

Here are the answers to your questions:

How to embed an Image in HTML? Why is the alt attribute so important?


To embed an image in HTML, you use the <img> tag, which requires the src attribute to specify the
image source.

Example:

html

<img src="image.jpg" alt="Description of image">

src (Source): Specifies the path to the image.

alt (Alternative text): Provides a text alternative for the image if it can't be displayed. It is crucial
for accessibility because screen readers use the alt text to describe images to visually impaired
users. It also improves SEO and helps when the image is missing or not loaded.

Why alt is important:

1. Accessibility: Helps visually impaired users by providing a description of the image.

258/411
2. SEO: Search engines use the alt text to understand the content of the image and index it
properly.

3. Fallback: If the image fails to load, the alt text will be displayed instead.

What are the differences between JPEG and PNG image formats?
JPEG (Joint Photographic Experts Group):

Best for: Photographs or images with complex colors.

Compression: Lossy compression (some image quality is lost during compression).

File Size: Smaller file size due to compression.

Transparency: Does not support transparency.

Quality: Lower image quality with higher compression, leading to some loss of detail and
sharpness.

PNG (Portable Network Graphics):

Best for: Images with transparency or images requiring sharpness, such as logos, icons, and
images with text.

Compression: Lossless compression (no data loss during compression).

File Size: Larger file size due to lossless compression.

Transparency: Supports transparent backgrounds.

Quality: Higher quality with lossless compression, preserving image details.

How to embed Video element in HTML? Why do we need multiple source


elements?
To embed a video in HTML, you use the <video> element. You can provide multiple <source>
elements within the <video> tag to ensure compatibility across different browsers and formats.

Example:

html

<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogv" type="video/ogg">

259/411
<source src="video.webm" type="video/webm">
Your browser does not support the video tag.
</video>

Why multiple <source> elements?: Different browsers support different video formats. For
instance, some browsers may support MP4, while others support Ogg or WebM. By providing
multiple sources, you ensure that the video will play in most browsers.

How to embed Audio element in HTML?


To embed an audio file in HTML, you use the <audio> element, similar to the <video> tag. You can
also use the <source> tag to provide different audio formats for browser compatibility.

Example:

html

<audio controls>
<source src="audio.mp3" type="audio/mp3">
<source src="audio.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>

controls : Adds play, pause, and volume controls to the audio player.

What are the Autoplay & Loop attributes in multimedia elements?


1. Autoplay:

The autoplay attribute automatically starts playing the media (video or audio) as soon as it is
ready, without user interaction.

Example:

html

<audio autoplay>
<source src="audio.mp3" type="audio/mp3">
</audio>

260/411
Note: Autoplay may be restricted in certain browsers, particularly for videos with sound, due
to user experience considerations.

2. Loop:

The loop attribute causes the media to restart automatically after it ends, creating a
continuous playback loop.

Example:

html

<video loop>
<source src="video.mp4" type="video/mp4">
</video>

Note: This is commonly used in background videos or short animations.

Let me know if you need further details!

Q. What are HTML Forms and what are its advantages?


02:19
Q. What are HTML Form Elements and their Main Attributes?
02:16
Q. How to Validate for empty input field in form?
00:49
Q. What is the role of the <textarea> element in a form?
01:11
Q. What are the Types of Input elements in a form?
02:01
Q. How to create radio buttons and checkboxes? How to group
them?
02:15
Q. What is the purpose of the <select> element in a form?

Here are the answers to your questions related to HTML forms:

What are HTML Forms and what are its advantages?


HTML Forms: HTML forms are used to collect user input, such as text, selections, and file uploads, and
send it to a server for processing. Forms are created using the <form> element in HTML.

261/411
Advantages:

1. User Interaction: Forms provide a way for users to input data and interact with websites.

2. Data Submission: They are used to submit data to a server for processing, like registration, login,
or feedback.

3. Customization: Forms can include different types of fields (text, radio buttons, checkboxes, etc.),
making them highly customizable.

4. Validation: HTML forms allow for both client-side and server-side validation of user input.

What are HTML Form Elements and their Main Attributes?


HTML form elements are used to create interactive controls in a form. Here are some of the most
commonly used form elements and their main attributes:

1. <input>:

Used for various input types like text, password, checkbox, etc.

Attributes: type , name , value , placeholder , required , maxlength , disabled

2. <textarea>:

Used for multi-line text input.

Attributes: name , rows , cols , placeholder , required

3. <button>:

Used for creating buttons.

Attributes: type , name , value

4. <select>:

Used to create dropdown menus.

Attributes: name , required

5. <label>:

Defines a label for an <input> element.

Attributes: for

6. <fieldset> and <legend>:

Used for grouping related elements in a form.

Attributes: disabled (for fieldset ), for (for legend )

262/411
How to Validate for empty input field in form?
To validate an empty input field in an HTML form, you can use the required attribute in the <input>
element. This will prevent form submission if the field is left empty.

Example:

html

<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>

In this case, if the user tries to submit the form without entering a name, the browser will display a
message and prevent submission.

What is the role of the <textarea> element in a form?


The <textarea> element is used for multi-line text input. It allows users to type in larger chunks of
text, such as comments, messages, or descriptions.

Attributes:

rows : Specifies the visible number of lines in the text area.

cols : Specifies the visible width of the text area in characters.

placeholder : Provides a short hint within the text area.

Example:

html

<textarea rows="4" cols="50" name="message" placeholder="Enter your message here...">


</textarea>

What are the Types of Input elements in a form?


HTML provides several types of <input> elements, which determine the type of data the user can
enter. Some common input types are:

263/411
1. text: Single-line text input.

2. password: Hidden text input for passwords.

3. email: Input for email addresses, which includes validation.

4. number: Input for numerical values.

5. radio: Radio buttons for selecting one option from a group.

6. checkbox: Checkbox for selecting multiple options.

7. submit: Button to submit the form.

8. reset: Button to reset the form values.

9. file: Allows file uploads.

10. date: Allows the user to select a date.

11. tel: For telephone numbers.

12. url: For URLs, with validation.

Example:

html

<input type="email" name="user_email">


<input type="password" name="user_password">
<input type="radio" name="gender" value="male"> Male
<input type="checkbox" name="subscribe"> Subscribe

How to create radio buttons and checkboxes? How to group them?


To create radio buttons and checkboxes in a form:

1. Radio buttons allow the user to select only one option from a group of options.

Example:

html

<label><input type="radio" name="color" value="red"> Red</label>


<label><input type="radio" name="color" value="blue"> Blue</label>

Grouping: Use the same name attribute for all radio buttons in the same group, as shown in
the example above. This ensures that only one radio button can be selected at a time.

2. Checkboxes allow the user to select one or more options.

264/411
Example:

html

<label><input type="checkbox" name="hobby" value="reading"> Reading</label>


<label><input type="checkbox" name="hobby" value="sports"> Sports</label>

Grouping: Checkboxes are grouped by using the same name attribute, but unlike radio
buttons, they can be selected independently.

What is the purpose of the <select> element in a form?


The <select> element is used to create a drop-down list, allowing the user to choose one or more
options from a list of predefined options. It contains <option> elements, which define the available
options for selection.

Example:

html

<select name="car" id="car">


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

Attributes: name is used to associate the element with a name, which is sent with the form data.
You can also use multiple if you want users to select multiple options.

Let me know if you need further clarification on any of these topics!

Q. What are top 10 Best Practices for writing HTML code?


03:39
Q. What is HTML5 Boilerplate code?
00:52
Q. How do you optimize an HTML website for Performance?
02:22
Q. What is SEO? What are 5 HTML Best Practices for SEO?
03:06
Q. What are the 5 steps required for HTML website deployment?

Here are the answers to your questions:

265/411
What are Top 10 Best Practices for Writing HTML Code?
1. Use Semantic HTML Tags:

Use semantic elements like <header> , <footer> , <main> , <section> , etc., to improve
accessibility and SEO.

2. Use Proper Indentation:

Indent your HTML code consistently to improve readability. Use 2 or 4 spaces for indentation,
depending on your project style guide.

3. Write Descriptive and Clear IDs and Classes:

Use meaningful and descriptive names for IDs and classes to make your code more readable
and maintainable.

4. Avoid Inline Styles:

Use external CSS files to style your pages, rather than using inline styles, which makes the
code harder to maintain.

5. Use Alt Text for Images:

Always include an alt attribute for images to improve accessibility and provide context for
search engines.

6. Keep Accessibility in Mind:

Add proper ARIA attributes and labels to improve accessibility for screen readers.

7. Validate Your HTML:

Use tools like the W3C Markup Validation Service to validate your HTML to ensure that your
code is free from errors and conforms to standards.

8. Use External CSS and JavaScript Files:

Instead of embedding large chunks of CSS and JavaScript in the HTML file, link to external files
to keep your HTML clean and minimize page load time.

9. Minimize the Use of <div> and <span> :

Use more meaningful HTML5 semantic elements instead of relying on <div> and <span>
which are non-semantic.

10. Use Proper HTML Document Structure:

Ensure that every document has the correct structure: <!DOCTYPE html> , <html> , <head> , and
<body> tags.

266/411
What is HTML5 Boilerplate Code?
HTML5 Boilerplate is a set of standard templates, configurations, and tools for building fast, robust,
and adaptable web apps or websites. It includes basic structure for HTML, CSS resets, and essential
JavaScript to ensure your website works well across different devices and browsers. The HTML5
Boilerplate also improves website performance and ensures best practices for web development.

How Do You Optimize an HTML Website for Performance?


Here are some key ways to optimize an HTML website for better performance:

1. Minify HTML, CSS, and JavaScript:

Minification removes unnecessary spaces, comments, and characters to reduce file size and
improve page loading speed.

2. Use Asynchronous JavaScript:

Load JavaScript asynchronously using the async or defer attribute to avoid blocking HTML
rendering.

3. Leverage Browser Caching:

Use proper HTTP headers to instruct browsers to cache static assets like images, stylesheets,
and scripts for future visits.

4. Optimize Images:

Compress and use appropriate image formats (e.g., WebP) to reduce the file size and loading
time.

5. Reduce HTTP Requests:

Minimize the number of requests made to the server by combining CSS and JavaScript files,
and reducing the number of images used.

6. Implement Lazy Loading:

Load images and other content only when they are needed (e.g., when they are in the
viewport).

7. Use Content Delivery Networks (CDNs):

Host static files (like images, CSS, and JavaScript) on CDNs to serve them from locations closer
to the user, improving loading times.

267/411
8. Enable GZIP Compression:

Use GZIP compression to reduce the size of your HTML, CSS, and JavaScript files before
sending them to the browser.

What is SEO? What are 5 HTML Best Practices for SEO?


SEO (Search Engine Optimization): SEO is the practice of optimizing a website or content to rank
higher on search engines like Google, improving visibility and organic traffic.

5 HTML Best Practices for SEO:

1. Use Descriptive Title Tags:

Ensure each page has a unique and descriptive <title> tag to summarize the page content.

2. Optimize Meta Tags:

Use relevant <meta> tags like description and keywords to provide additional information
about the page.

3. Use Semantic HTML Tags:

Proper use of semantic tags (e.g., <article> , <header> , <footer> ) improves content clarity
and accessibility, which boosts SEO.

4. Ensure Mobile-Friendly Design:

Use responsive web design techniques (like the viewport meta tag) to ensure your site works
well on all screen sizes, which is important for SEO.

5. Use Alt Attributes for Images:

Provide descriptive alt text for images to help search engines understand the content of the
images and improve image search results.

What Are the 5 Steps Required for HTML Website Deployment?


1. Prepare Your Files:

Ensure all your HTML, CSS, JavaScript, and image files are ready and properly organized for
deployment.

2. Test Locally:

Test your website locally to ensure it works properly across different browsers and devices.

268/411
3. Choose a Web Hosting Provider:

Select a web hosting provider that suits your needs (e.g., shared hosting, VPS, or cloud
hosting).

4. Upload Your Files:

Upload your website files to the hosting server using FTP/SFTP or a web hosting control panel
(e.g., cPanel).

5. Configure Domain Name and DNS Settings:

Set up your domain name and point it to your hosting provider by updating the DNS settings
to ensure your website is accessible.

Let me know if you need further explanation or have more questions!

Q. What is Responsive Design?


01:07
Q. What are the top 3 things required to make a website
Responsive in HTML?
01:36
Q. What are some Responsive Design Frameworks for HTML &
CSS?
00:58
Q. What are HTML Entities? How do you display special characters
in HTML?
01:00
Q. What are the Top 5 Emerging Trends in HTML development?

Here are the answers to your questions:

What is Responsive Design?


Responsive Design refers to an approach in web design and development where a website is built to
provide an optimal viewing experience across a wide range of devices (from desktop computers to
mobile phones). The layout and elements on the page automatically adjust, resize, or rearrange to fit
the screen size, ensuring usability and accessibility for the user.

What are the Top 3 Things Required to Make a Website Responsive in HTML?

269/411
1. Viewport Meta Tag:

Add the <meta name="viewport" content="width=device-width, initial-scale=1.0"> tag in


the <head> section of the HTML document to control the layout on mobile browsers and set
the scaling.

2. Flexible Grid Layout:

Use percentage-based widths instead of fixed pixel widths for the layout. This allows elements
to scale proportionally according to the screen size.

3. Media Queries:

Use CSS media queries to apply different styles based on the screen size, orientation, and
resolution. This allows for changing layout, font sizes, or other styles based on the device’s
characteristics.

What are Some Responsive Design Frameworks for HTML & CSS?
1. Bootstrap:

A widely used framework that provides a grid system, pre-built responsive design
components, and CSS utilities for mobile-first design.

2. Foundation:

A responsive front-end framework that offers a flexible grid system and mobile-first
components, which can be customized according to your needs.

3. Tailwind CSS:

A utility-first CSS framework that allows developers to build custom responsive designs with
minimal effort by using pre-defined utility classes.

What are HTML Entities? How do you Display Special Characters in HTML?
HTML Entities are special codes that represent characters that may have special meanings in HTML
(like < , > , or & ), or characters that are not easily typed on a keyboard, such as accented letters or
mathematical symbols. They are written as &entity; , such as &lt; for < , &gt; for > , and &amp;
for & .

You can display special characters by using their corresponding HTML entity codes in your HTML
markup. For example:

270/411
&lt; represents <

&gt; represents >

&amp; represents &

&copy; represents ©

What are the Top 5 Emerging Trends in HTML Development?


1. HTML5 Advancements:

HTML5 continues to evolve, offering new semantic elements like <article> , <section> ,
<nav> , and <footer> , which improve SEO, accessibility, and content structure.

2. Web Components:

Web Components allow developers to create reusable custom elements with encapsulated
styles and functionality, promoting modular design and reusability.

3. Progressive Web Apps (PWAs):

PWAs provide a native app-like experience using HTML, CSS, and JavaScript, allowing websites
to work offline, load quickly, and be installed on mobile devices.

4. Improved Accessibility:

Increased focus on creating accessible websites with better use of ARIA (Accessible Rich
Internet Applications) roles, labels, and attributes, ensuring that websites are usable by people
with disabilities.

5. Responsive Images:

The use of the <picture> element and srcset attribute allows developers to deliver different
image sizes based on the screen resolution or device, improving loading times and
performance.

Let me know if you need more details on any of these topics!

Q. What is CSS? What are the 5 ways to Implement CSS in HTML?


01:34
Q. What is Inline Style in CSS? When to use it in real applications?
01:03
Q. What is Internal Stylesheet in CSS? When to use it in real
applications?
01:34
Q. What is External Stylesheet in CSS? When to use it in real
applications?

271/411
01:36
Q. What are the 5 advantages of external stylesheet?
01:41
Q. How do you Include CSS in a webpage or HTML?
00:41
Q. How to implement CSS using @import rule?
02:01
Q. What is CSS Preprocessors? What is SCSS?
03:11
Q. What are the 3 Types of CSS Preprocessors?

Here are the answers to your questions about CSS:

What is CSS? What are the 5 Ways to Implement CSS in HTML?


CSS (Cascading Style Sheets) is a style sheet language used to define the presentation of a web page
written in HTML or XML. It controls the layout, design, colors, fonts, spacing, and overall look of the
web pages.

The 5 ways to implement CSS in HTML are:

1. Inline CSS: Directly within the HTML element using the style attribute.

2. Internal CSS: Defined within the <style> tag in the <head> section of the HTML document.

3. External CSS: Linked to an HTML document through an external CSS file using the <link> tag.

4. CSS @import Rule: Imports external CSS files into a CSS file.

5. CSS in JavaScript (CSS-in-JS): Defining CSS directly inside JavaScript files, commonly used with
modern frameworks like React.

What is Inline Style in CSS? When to Use It in Real Applications?


Inline Style is a way to apply CSS rules directly to an individual HTML element using the style
attribute. For example:

html

<p style="color: red; font-size: 16px;">This is a paragraph with inline styles.</p>

When to Use:

272/411
Inline styles are rarely used for large applications but can be useful for quick, specific styling on a
single element.

It is best used for dynamically generated content (e.g., in JavaScript) or if styles need to be applied
conditionally on a single element.

What is Internal Stylesheet in CSS? When to Use It in Real Applications?


An Internal Stylesheet is CSS code written inside a <style> tag in the <head> section of the HTML
document. It applies styles to elements within that specific HTML page.

When to Use:

When you want to apply CSS to a single page only, without affecting other pages in the website.

It is useful for small websites or prototypes where external CSS might not be necessary.

html

<head>
<style>
p {
color: blue;
}
</style>
</head>

What is External Stylesheet in CSS? When to Use It in Real Applications?


An External Stylesheet is a separate CSS file that is linked to an HTML document via the <link> tag.
This method allows you to use the same stylesheet across multiple pages.

When to Use:

Ideal for large websites where you need to apply the same styles across multiple pages.

Helps maintain a clean, organized codebase and promotes reusability.

html

<head>
<link rel="stylesheet" href="styles.css">

273/411
</head>

What Are the 5 Advantages of External Stylesheet?


1. Separation of Concerns: Keeps HTML and CSS separate, improving readability and maintainability.

2. Reusability: The same stylesheet can be applied to multiple web pages, reducing redundancy.

3. Improved Load Time: External CSS files can be cached by browsers, reducing page load times for
subsequent visits.

4. Easier Maintenance: Changes in the stylesheet are automatically reflected across all linked HTML
pages, making updates easier.

5. Cleaner Code: HTML files remain cleaner and more readable, without inline or internal CSS clutter.

How Do You Include CSS in a Webpage or HTML?


CSS can be included in an HTML document in three ways:

1. Inline CSS: Using the style attribute within HTML tags.

2. Internal CSS: Using a <style> tag in the <head> section of the HTML document.

3. External CSS: Linking to an external CSS file using the <link> tag.

How to Implement CSS Using @import Rule?


The @import rule allows you to import one CSS file into another CSS file. This can be used in an
external stylesheet to import additional stylesheets.

css

@import url("styles.css");

Note: @import can also be used in the <style> section, but using it in external files might cause
slower page load times compared to using <link> .

274/411
What is CSS Preprocessors? What is SCSS?
CSS Preprocessors are scripting languages that extend CSS with features like variables, nesting,
mixins, and functions, making CSS easier to write and maintain. The most popular CSS preprocessors
are Sass, LESS, and Stylus.

SCSS (Sassy CSS) is a syntax of Sass (Syntactically Awesome Stylesheets). It provides the same features
as Sass but with a syntax more similar to regular CSS, allowing you to write CSS inside .scss files.

What Are the 3 Types of CSS Preprocessors?


1. Sass (Syntactically Awesome Stylesheets): Offers both SCSS (more CSS-like syntax) and indented
syntax (which uses indentation rather than curly braces and semicolons).

2. LESS: A preprocessor that extends CSS with variables, mixins, and functions, offering easier and
more maintainable code.

3. Stylus: A CSS preprocessor similar to Sass and LESS, but with a more flexible syntax that allows for
optional semicolons, braces, and parentheses.

Let me know if you need more details!

Q. What are Selectors in CSS? How many types of selectors are


there?
01:05
Q. Difference between ID, Element & Class selector? When to use
which selector?
03:23
Q. What are Universal selectors?
00:51
Q. What are the Descendant Selectors in CSS?
02:18
Q. What are Attribute Selectors in CSS? What are it’s 5 Types?
02:57
Q. What are Child Selectors in CSS?
01:26
Q. How Child Selector is different from Descendent selectors?
00:24
Q. What are Pseudo-class Selector and Pseudo-element Selector?

Here are the answers to your questions about CSS selectors:

275/411
What are Selectors in CSS? How Many Types of Selectors Are There?
Selectors in CSS are used to select HTML elements on which styles will be applied. They target specific
elements based on various criteria like their type, class, id, attributes, or relationship to other
elements.

There are several types of selectors in CSS:

1. Universal Selector ( * ): Targets all elements on the page.

2. Type Selector (Element Selector): Selects all elements of a specific type (e.g., p , h1 , div ).

3. Class Selector ( .classname ): Selects elements with a specific class attribute.

4. ID Selector ( #idname ): Selects a specific element with a unique ID.

5. Descendant Selector: Selects elements nested within a parent element.

6. Child Selector: Selects direct child elements of a specific parent.

7. Attribute Selector: Selects elements based on their attributes.

8. Pseudo-classes: Selects elements based on their state (e.g., :hover , :focus ).

9. Pseudo-elements: Selects parts of an element (e.g., ::before , ::after ).

Difference Between ID, Element & Class Selector? When to Use Which
Selector?
ID Selector ( #idname ):

Targets a unique element on the page with a specific id attribute.

Use it when you need to target a single, unique element.

Example: #header { color: blue; }

Element (Type) Selector ( element ):

Targets all elements of a specific type.

Use it when you want to apply styles to all instances of that element type.

Example: h1 { font-size: 24px; }

Class Selector ( .classname ):

Targets elements with a specific class attribute, allowing you to apply styles to multiple
elements.

276/411
Use it when you want to apply the same style to several elements.

Example: .btn { background-color: red; }

What are Universal Selectors?


The Universal Selector ( * ) selects all elements on a page. It applies styles universally to every element
unless overridden by more specific selectors.

Example:

css

* {
margin: 0;
padding: 0;
}

This rule removes margins and padding from every element on the page.

What are the Descendant Selectors in CSS?


A Descendant Selector targets elements that are nested within a specific parent element, no matter
how deeply nested they are.

Example:

css

div p {
color: red;
}

This targets all <p> elements inside any <div> element, regardless of how deeply nested they are
within <div> .

What are Attribute Selectors in CSS? What Are Its 5 Types?


Attribute Selectors in CSS allow you to target elements based on their attribute values.

277/411
The five types of attribute selectors are:

1. [attr] : Selects elements that have the specified attribute. Example: [type] (selects all elements
with a type attribute).

2. [attr="value"] : Selects elements with a specific attribute value. Example: [type="text"]


(selects all <input> elements with the type attribute set to "text" ).

3. [attr~="value"] : Selects elements whose attribute value contains a specified word (separated by
spaces). Example: [class~="btn"] (selects elements with a class that contains the word "btn" ).

4. [attr|="value"] : Selects elements with an attribute value that starts with the specified value or is
an exact match with the specified value, followed by a hyphen. Example: [lang|="en"] (selects
elements with a lang attribute value of "en" or "en-US" ).

5. [attr^="value"] : Selects elements whose attribute value starts with the specified value. Example:
[href^="https"] (selects links starting with https ).

6. [attr$="value"] : Selects elements whose attribute value ends with the specified value. Example:
[src$=".jpg"] (selects images ending with .jpg ).

What are Child Selectors in CSS?


A Child Selector targets direct child elements of a specified parent element. This is more specific than
descendant selectors, which select elements at any level of nesting.

Example:

css

div > p {
color: green;
}

This will only select <p> elements that are direct children of a <div> , not deeper nested <p>
elements.

How Child Selector Is Different From Descendant Selectors?


Child Selector ( > ): Selects only direct children of a parent element.

Descendant Selector (space): Selects all descendants (children, grandchildren, etc.) of a parent
element, regardless of depth.

278/411
Example:

css

/* Child Selector */
div > p {
color: blue;
}

/* Descendant Selector */
div p {
color: red;
}

The child selector only targets <p> elements directly inside a <div> , while the descendant selector
targets all <p> elements inside a <div> , including nested ones.

What are Pseudo-class Selector and Pseudo-element Selector?


Pseudo-class Selector ( : ): Targets elements based on their state or position. For example:

:hover : Targets an element when it is hovered over.

:focus : Targets an element when it is focused (like an input field).

:first-child : Targets the first child element of a parent.

Example:

css

a:hover {
color: red;
}

Pseudo-element Selector ( :: ): Targets specific parts of an element, such as the first letter or line
of a text, or content before or after an element.

::before : Inserts content before an element.

::after : Inserts content after an element.

::first-letter : Styles the first letter of an element.

Example:

279/411
css

p::first-letter {
font-size: 2em;
}

Let me know if you need further clarification!

Q. Explain the concept of the Box Model in CSS.


02:00
Q. What is the difference between Padding and Margin?
01:36
Q. What is the difference between display: inline & display: block?
01:32
Q. What is the difference between display: inline and display:
inlineblock?
01:41
Q. What is z-index property in CSS? How same z-index elements
will be displayed?
02:16
Q. What is the role of float property in CSS?
02:15
Q. What is the difference between position: relative/ absolute/
fixed?

Here are the explanations for the concepts related to the Box Model and CSS positioning:

Explain the Concept of the Box Model in CSS


The CSS Box Model is a fundamental concept that describes how elements are structured and sized in
web design. Every element in HTML is considered a box, and the box model defines how space around
and inside elements is calculated.

The Box Model consists of the following components:

1. Content: The actual content of the element (e.g., text, images).

2. Padding: The space between the content and the border. It is used to create space around the
content inside the element.

3. Border: The boundary surrounding the padding (and content). It can have various styles, widths,
and colors.

4. Margin: The outermost space around the border. It separates the element from other surrounding
elements.

280/411
Here’s a visual representation:

lua

+----------------------------+
| Margin |
| +------------------------+ |
| | Border | |
| | +------------------+ | |
| | | Padding | | |
| | | +------------+ | | |
| | | | Content | | | |
| | | +------------+ | | |
| | +------------------+ | |
| +------------------------+ |
+----------------------------+

The total width and height of an element are calculated as:

sql

Total width = content width + left padding + right padding + left border + right border +
left margin + right margin

What is the Difference Between Padding and Margin?


Padding is the space inside an element, between the content and the border. It pushes the content
away from the edge of the element.

Margin is the space outside the element, between the border and the surrounding elements. It
creates space between the element and other elements.

Key Differences:

1. Padding affects the size of the element (content area), but Margin does not.

2. Padding is part of the element's box and can be styled, whereas Margin separates elements from
each other.

What is the Difference Between display: inline and display: block ?


display: inline :

281/411
The element is displayed inline with other content, meaning it doesn't start on a new line.

It only takes up as much width as necessary for its content.

Cannot have width, height, or vertical margin/padding applied (though it can have horizontal
padding/margin).

display: block :

The element starts on a new line and takes up the full width of its container (by default).

It can have width, height, margin, and padding applied to all sides.

Examples of block-level elements: <div> , <p> , <h1> .

What is the Difference Between display: inline and display: inline-


block ?

display: inline :

The element behaves like text, flowing along with other inline elements on the same line.

It does not respect width or height properties, and margins/paddings only work horizontally.

display: inline-block :

The element behaves like an inline element (appears on the same line), but it also respects
width and height properties.

Can have both horizontal and vertical margins/paddings.

Key Difference: inline-block combines the characteristics of both inline and block elements.

What is z-index Property in CSS? How Will Same z-index Elements Be


Displayed?
The z-index property controls the stacking order of elements on the z-axis (i.e., which element will be
in front of or behind others when they overlap).

Higher z-index values will appear in front of elements with lower z-index values.

Elements with the same z-index value will be displayed in the order they appear in the HTML
(the one declared later will be in front).

Example:

282/411
css

div1 {
position: absolute;
z-index: 1;
}

div2 {
position: absolute;
z-index: 2;
}

In this example, div2 will appear above div1 .

What is the Role of the float Property in CSS?


The float property is used to position elements to the left or right within their container, allowing
content to wrap around them.

Common uses:

Placing images to the left or right of text.

Creating multi-column layouts.

However, it can cause layout issues, and modern layout techniques like Flexbox and CSS Grid are
recommended over using float .

Example:

css

img {
float: left;
margin-right: 15px;
}

This will make the image float to the left, allowing text to wrap around it.

What is the Difference Between position: relative , position: absolute ,


and position: fixed ?
1. position: relative :

283/411
The element is positioned relative to its normal position in the document flow.

You can move it using top , right , bottom , and left properties, but the space it originally
occupied in the document flow is still reserved.

2. position: absolute :

The element is positioned relative to the nearest positioned ancestor (not static ). If there is
no such ancestor, it is positioned relative to the initial containing block (usually the <html>
element).

It is removed from the document flow, meaning it does not take up space in the layout.

3. position: fixed :

The element is positioned relative to the viewport (the browser window), meaning it will stay in
the same place even when the page is scrolled.

It is also removed from the document flow.

Key Differences:

Relative: The element stays in the flow of the document but can be moved relative to its position.

Absolute: The element is removed from the flow and positioned relative to an ancestor.

Fixed: The element is removed from the flow and fixed to the viewport.

Let me know if you need further clarifications!

Q. What is the role of meta viewport tag?


03:07
Q. What are Media Queries in CSS?
01:24
Q. What is display: flex in CSS?
02:13
Q. What is CSS Grid Layout in CSS?
01:11
Q. How can you create a Sticky Header in CSS?
00:39
Q. What are the 5 best practices for creating a Responsive Design
using CSS?

Here are the explanations for the meta viewport tag, CSS Flexbox, CSS Grid, and other related
concepts:

What is the Role of the Meta Viewport Tag?

284/411
The meta viewport tag is used to control the layout of the webpage on mobile devices. It tells the
browser how to scale the content, allowing the page to be responsive and fit correctly on various
screen sizes.

Example:

html

<meta name="viewport" content="width=device-width, initial-scale=1.0">

width=device-width : Ensures the width of the page is equal to the width of the device screen.

initial-scale=1.0 : Sets the initial zoom level when the page is first loaded (1.0 means no zoom).

Without this tag, websites on mobile devices might appear zoomed out or not scale properly to the
screen width.

What Are Media Queries in CSS?


Media Queries in CSS allow you to apply different styles based on specific conditions like screen width,
height, device type, or orientation. They are crucial for creating responsive designs that adjust to
various devices.

Example:

css

@media (max-width: 768px) {


body {
background-color: lightblue;
}
}

This media query applies the background color lightblue to the body if the viewport is 768px wide or
smaller (common for tablets and mobile devices).

Key conditions:

max-width and min-width control layout based on screen size.

orientation checks if the device is in portrait or landscape mode.

285/411
What is display: flex in CSS?
The display: flex property is used to create a flexible layout that distributes space along a row or
column, making it easier to align items within a container.

When you apply display: flex to a parent container, the children (flex items) are aligned in a flexible
way.

Key features:

justify-content : Aligns items horizontally (left, center, right, or distributed).

align-items : Aligns items vertically (top, center, bottom).

flex-direction : Defines whether the items should be arranged in a row or column.

Example:

css

.container {
display: flex;
justify-content: space-between;
}

This makes the items inside .container space out evenly across the container.

What is CSS Grid Layout?


CSS Grid Layout is a two-dimensional layout system that allows you to create complex layouts with
rows and columns. It gives you control over both horizontal and vertical alignment of elements within a
container.

Key properties:

grid-template-columns and grid-template-rows : Define the number and size of the grid's
columns and rows.

grid-gap : Specifies the spacing between grid items.

grid-column and grid-row : Define how items span across columns or rows.

Example:

css

.container {
display: grid;

286/411
grid-template-columns: 1fr 2fr 1fr;
}

This creates a 3-column grid, with the second column being twice the size of the others.

How Can You Create a Sticky Header in CSS?


A sticky header stays fixed at the top of the page even when the user scrolls down.

You can create a sticky header with the position: sticky property, and it only works when the
element is within the scrollable content.

Example:

css

.header {
position: sticky;
top: 0;
background-color: #fff;
z-index: 100;
}

position: sticky keeps the element fixed once it reaches the top of the page.

top: 0 specifies that the element will stick to the top.

What Are the 5 Best Practices for Creating a Responsive Design Using CSS?
1. Use a Fluid Grid Layout: Instead of fixed-width elements, use relative units like percentages or em
to create flexible, fluid layouts.

Example: width: 50% rather than width: 500px .

2. Use Media Queries: Apply different styles for different screen sizes to ensure your design looks
great on all devices.

Example: @media (max-width: 600px) to apply styles for smaller screens.

3. Optimize for Mobile First: Start designing for smaller screens (mobile-first) and scale up to larger
screens using media queries.

Use max-width for desktop layouts, and min-width for mobile layouts.

287/411
4. Set the Viewport Properly: Always use the meta viewport tag to ensure your content scales
properly on mobile devices.

Example: <meta name="viewport" content="width=device-width, initial-scale=1.0"> .

5. Use Flexbox and CSS Grid: These modern layout systems provide flexibility in designing
responsive layouts without using floats or positioning.

Flexbox for one-dimensional layouts (row or column).

Grid for two-dimensional layouts (both rows and columns).

These practices will ensure your website is responsive and performs well across a variety of screen
sizes and devices.

Let me know if you need more information on any of these concepts!

Q. What is Bootstrap? What are the other 5 responsive design


frameworks?
01:38
Q. What are the 5 Advantages of using Bootstrap?
02:04
Q. What are the 2 ways to include Bootstrap framework for your
website.
01:57
Q. Explain the Grid System in Bootstrap?
02:27
Q. What is the difference between col-xs, col-sm, col-md, col-lg &
col-xl?
01:59
Q. What are Bootstrap Components? What are Top 10 bootstrap
components?
02:26
Q. What is a Bootstrap Modal component?
01:14
Q. What is a Bootstrap Navigation component?
00:51
Q. What is Bootstrap Carousel component?
00:51
Q. Explain the difference between Bootstrap's container and
container-fluid?

What is Bootstrap? What are the Other 5 Responsive Design Frameworks?

288/411
Bootstrap is a popular front-end framework developed by Twitter. It is used to build responsive and
mobile-first websites and web applications. Bootstrap provides a collection of pre-built, customizable
components (e.g., buttons, forms, navigation bars) and a grid system for creating layouts. It helps
developers save time by avoiding the need to code from scratch and ensures that designs are
consistent across devices.

Other responsive design frameworks include:

1. Foundation: Developed by Zurb, it's a responsive front-end framework with a strong emphasis on
customization and accessibility.

2. Bulma: A modern CSS framework based on Flexbox, with a clean design and simple syntax.

3. Tailwind CSS: A utility-first CSS framework that allows for easy customization using pre-defined
classes.

4. Materialize: A CSS framework based on Google’s Material Design principles.

5. UIkit: A lightweight and modular front-end framework with customizable components and a
responsive grid system.

What are the 5 Advantages of Using Bootstrap?


1. Responsive Design: Bootstrap automatically adjusts the layout based on screen size, providing an
optimal viewing experience on all devices.

2. Pre-designed Components: Bootstrap offers a wide variety of pre-built UI components like


buttons, navigation bars, alerts, and modals, saving time for developers.

3. Grid System: Bootstrap includes a flexible 12-column grid system, making it easy to create
complex layouts that adjust to different screen sizes.

4. Cross-browser Compatibility: Bootstrap is compatible with all modern browsers (Chrome, Firefox,
Safari, Edge, etc.), ensuring consistent behavior across different environments.

5. Customization: Bootstrap is highly customizable with themes, and developers can override the
default styles to match their design preferences.

What are the 2 Ways to Include the Bootstrap Framework for Your Website?
1. Using CDN (Content Delivery Network):

You can link Bootstrap directly from a CDN, which is the easiest way. This method requires no
file downloading.

289/411
html

<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
</script>

2. Download Bootstrap Files:

Download the Bootstrap files and include them in your project. This method gives you more
control over your assets.

html

<link rel="stylesheet" href="path/to/bootstrap.min.css">


<script src="path/to/bootstrap.min.js"></script>

Explain the Grid System in Bootstrap


The Bootstrap grid system is based on a 12-column layout. It allows you to create flexible and
responsive layouts by dividing your page into 12 columns. You can control the layout by specifying how
many columns a particular element should span.

Rows: Wrap the columns inside a .row container to create a horizontal group of columns.

Columns: Use classes like .col- , .col-sm- , .col-md- to define how many columns an element
should span, depending on the screen size.

Example:

html

<div class="row">
<div class="col-md-4">Column 1</div>
<div class="col-md-4">Column 2</div>
<div class="col-md-4">Column 3</div>
</div>

290/411
What is the Difference Between col-xs , col-sm , col-md , col-lg & col-xl ?
These classes represent different screen sizes and specify how columns behave at those breakpoints.
They are used to make your layout responsive and adjust to different screen sizes.

1. col-xs (extra small): For screens less than 576px (phones).

2. col-sm (small): For screens 576px or larger (small tablets).

3. col-md (medium): For screens 768px or larger (tablets).

4. col-lg (large): For screens 992px or larger (desktops).

5. col-xl (extra-large): For screens 1200px or larger (larger desktops).

Example:

html

<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">Column 1</div>
<div class="col-xs-12 col-sm-6 col-md-4">Column 2</div>
<div class="col-xs-12 col-sm-12 col-md-4">Column 3</div>
</div>

What are Bootstrap Components? What are Top 10 Bootstrap Components?


Bootstrap components are pre-designed, reusable UI elements that help speed up the web
development process. Some of the most commonly used components are:

1. Navbar: A navigation bar for your website.

2. Cards: Flexible content containers with options for headers, footers, and content.

3. Buttons: Pre-designed buttons with various styles and sizes.

4. Modals: Popup dialog boxes for user interactions.

5. Alerts: Displaying messages or notifications to users.

6. Forms: Pre-styled form controls like input fields, checkboxes, and radio buttons.

7. Carousel: A responsive, image-based slideshow component.

8. Dropdowns: Menus that display options when clicked.

9. Tooltips: Small information boxes that appear when you hover over an element.

10. Progress Bars: Display progress in a visual bar format.

291/411
What is a Bootstrap Modal Component?
A Bootstrap modal is a dialog box that pops up over the current page. It is often used for notifications,
forms, or images that require user interaction. You can customize the modal content and appearance.

Example:

html

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">


Launch modal
</button>

<div class="modal" id="myModal">


<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h5 class="modal-title">Modal Header</h5>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<!-- Modal Body -->
<div class="modal-body">
Content goes here.
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

What is a Bootstrap Navigation Component?


A Bootstrap navigation component is used to create responsive navigation menus (like top menus,
side menus, or tab-based navigation) with support for dropdowns, active states, and more.

Example:

html

<nav class="navbar navbar-expand-lg navbar-light bg-light">


<a class="navbar-brand" href="#">Navbar</a>

292/411
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
</ul>
</div>
</nav>

What is Bootstrap Carousel Component?


A Bootstrap carousel is a component that allows you to display a series of images or content slides in
a rotating manner. It supports features like automatic sliding and manual control via navigation
buttons.

Example:

html

<div id="carouselExample" class="carousel slide" data-ride="carousel">


<div class="carousel-inner">
<div class="carousel-item active">
<img src="image1.jpg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="image2.jpg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="image3.jpg" class="d-block w-100" alt="...">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">

293/411
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExample" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a

Explain Angular Routing in detail-


Creating A Navigation Link With “routerLink” Directive
Creating A NavBar Using Routes

Passing Route Parameters (Dynamic Routing)

IQ - Dynamic Routing

Wildcard Routes - Displaying The ‘404’ Page


03:19
IQ - Wildcard Routes
01:14
Understanding Nested Routes
02:28
IQ - Nested Routes
01:17
Task - Creating a multi-level menu
03:16
Redirecting Routes
04:10
IQ - Redirecting Routes

Understanding ActivatedRoute
04:51
IQ - ActivatedRoute
01:50
Query Parameters In Routing
04:17
IQ - Query Parameters In Routing
01:37
Navigating Routes
06:57
IQ - navigate() method

Angular Routing Explained in Detail


Angular Routing is a mechanism used to navigate between views or components based on the URL
path. It helps in developing Single Page Applications (SPA) by loading different components into a

294/411
single page without reloading the entire page. Angular's @angular/router module allows for defining
different routes and provides navigation features like dynamic routing, nested routes, and query
parameters.

Creating a Navigation Link with routerLink Directive


To create a navigation link, you use the routerLink directive to bind a route path to an element
(usually a link or button).

Example:

html

<a [routerLink]="['/home']">Home</a>

In this example, the user will be navigated to the "home" route when they click on the "Home" link.

Creating a NavBar Using Routes


A navigation bar is created by defining multiple routerLink directives for different routes.

Example:

html

<nav>
<ul>
<li><a [routerLink]="['/home']">Home</a></li>
<li><a [routerLink]="['/about']">About</a></li>
<li><a [routerLink]="['/contact']">Contact</a></li>
</ul>
</nav>

Here, clicking on each link will navigate to the respective component.

Passing Route Parameters (Dynamic Routing)


In Angular, dynamic routing allows passing parameters to components through the URL.

295/411
Example:

html

<a [routerLink]="['/product', productId]">Product</a>

The component associated with the route will receive the productId parameter.

In the component:

typescript

import { ActivatedRoute } from '@angular/router';

export class ProductComponent {


constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.route.paramMap.subscribe(params => {
let productId = params.get('productId');
console.log(productId);
});
}
}

Wildcard Routes - Displaying the ‘404’ Page


Wildcard routes allow you to handle unknown URLs by redirecting them to a ‘404’ or error page.

Example:

typescript

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: '**', component: PageNotFoundComponent } // Wildcard route
];

The ** is used for the wildcard route, and it captures all undefined paths.

Understanding Nested Routes

296/411
Nested routes allow you to define routes within other routes, creating child routes for a parent
component. This is useful for layouts with sections or tabs.

Example:

typescript

const routes: Routes = [


{
path: 'products', component: ProductsComponent,
children: [
{ path: 'details/:id', component: ProductDetailsComponent }
]
}
];

In the parent component, you’ll have an <router-outlet> to load the child routes.

Redirecting Routes
In some cases, you may want to redirect the user to a different route.

Example:

typescript

const routes: Routes = [


{ path: 'old-route', redirectTo: '/new-route', pathMatch: 'full' }
];

The redirectTo parameter specifies the new route to navigate to, and pathMatch determines how
the route path is matched (e.g., 'full' matches the entire path).

Understanding ActivatedRoute
ActivatedRoute provides access to route parameters, query parameters, and other information
related to the currently active route.

Example:

typescript

297/411
import { ActivatedRoute } from '@angular/router';

export class ProductComponent {


constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {
this.activatedRoute.params.subscribe(params => {
const id = params['id']; // Get route parameter 'id'
console.log(id);
});
}
}

Query Parameters in Routing


Query parameters are used to pass additional data in the URL, and they are often used to filter or
search content.

Example of passing query parameters:

html

<a [routerLink]="['/search']" [queryParams]="{ term: 'Angular' }">Search</a>

In the component, you can access the query parameters as:

typescript

import { ActivatedRoute } from '@angular/router';

export class SearchComponent {


constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
const term = params['term'];
console.log(term);
});
}
}

298/411
Navigating Routes
You can programmatically navigate between routes using the Router service's navigate() method.

Example:

typescript

import { Router } from '@angular/router';

export class AppComponent {


constructor(private router: Router) {}

goToHome() {
this.router.navigate(['/home']);
}
}

The navigate() method allows you to specify the target route, either as a string or an array of path
segments.

IQ - Wildcard Routes
Wildcard routes are designed to catch all undefined routes and redirect users to a custom page,
typically a '404' error page. They are essential in handling any unknown routes gracefully.

Example:

typescript

{ path: '**', component: NotFoundComponent }

This ensures that any route not matching a defined path will be redirected to the NotFoundComponent .

IQ - Redirecting Routes
Redirecting routes can be used to send users to a new path when they try to access a deprecated or old
route.

Example:

typescript

299/411
{ path: 'old', redirectTo: '/new', pathMatch: 'full' }

This redirect rule helps users transition seamlessly to new URLs without breaking links.

IQ - ActivatedRoute
ActivatedRoute provides essential information about the active route such as route parameters,
query parameters, and route configuration. It's often used in components to access route-specific data.

Example:

typescript

import { ActivatedRoute } from '@angular/router';

export class PostComponent {


constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.route.snapshot.paramMap.get('id'); // Access route parameter
}
}

IQ - Query Parameters in Routing


Query parameters are commonly used in Angular routing to pass additional, optional information in
the URL. They are helpful for filtering, sorting, or providing extra context.

Example:

html

<a [routerLink]="['/results']" [queryParams]="{ page: 1, sortBy: 'date' }">Search Results</a>

In the component:

typescript

import { ActivatedRoute } from '@angular/router';

export class ResultsComponent {

300/411
constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
const page = params['page'];
const sortBy = params['sortBy'];
console.log(`Page: ${page}, SortBy: ${sortBy}`);
});
}
}

IQ - navigate() Method
The navigate() method allows for programmatic navigation between routes. It's commonly used
when actions like button clicks or form submissions should trigger a route change.

Example:

typescript

import { Router } from '@angular/router';

export class DashboardComponent {


constructor(private router: Router) {}

navigateToProfile() {
this.router.navigate(['/profile']);
}
}

This method is often used to implement navigation within complex applications without relying on
routerLink in templates.

Understanding Slice Pipe


03:04
Task - Page navigation using slice pipe (Part-1)
05:25
Task - Page navigation using slice pipe (Part-2)
06:39
Understanding Number pipe
03:10
Task - Pound to Kg Converter Using Number Pipe
04:40

301/411
Understanding JSON Pipe
01:58
Displaying Table Data To JSON string

Understanding the Slice Pipe


The Slice Pipe is used to create a subset of an array or string by taking a portion of the data. It can
be used to display a range of items from an array or a substring from a string.

Syntax:

html

{{ data | slice:start:end }}

start : The starting index from where you want to slice.

end : (optional) The ending index (not inclusive). If omitted, the slice goes until the end of the array
or string.

Example:

html

<p>{{ 'Hello, Angular!' | slice:7:13 }}</p> <!-- Output: Angular -->

In the context of an array:

html

<ul>
<li *ngFor="let item of items | slice:0:3">{{ item }}</li> <!-- Output: First 3 items -->
</ul>

Task - Page Navigation Using Slice Pipe (Part-1)


When dealing with large datasets, it's common to paginate the data. The slice pipe can help by only
displaying a portion of the dataset at a time.

Example of pagination setup:

html

<ul>
<li *ngFor="let item of items | slice:pageIndex:pageIndex+pageSize">{{ item }}</li>

302/411
</ul>

Here, pageIndex and pageSize control which items are displayed, and they change dynamically when
you move between pages.

Task - Page Navigation Using Slice Pipe (Part-2)


This is a continuation of the previous task, where you would dynamically modify the pageIndex value
as the user navigates through the pages.

For example:

typescript

export class PaginationComponent {


items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
pageIndex = 0;
pageSize = 3;

goToNextPage() {
if (this.pageIndex + this.pageSize < this.items.length) {
this.pageIndex += this.pageSize;
}
}

goToPreviousPage() {
if (this.pageIndex - this.pageSize >= 0) {
this.pageIndex -= this.pageSize;
}
}
}

And in the template:

html

<ul>
<li *ngFor="let item of items | slice:pageIndex:pageIndex+pageSize">{{ item }}</li>
</ul>

<button (click)="goToPreviousPage()">Previous</button>
<button (click)="goToNextPage()">Next</button>

303/411
Understanding the Number Pipe
The Number Pipe is used to format a number according to a specific format. It allows you to specify
the number of decimal places, whether the number should be grouped by thousands, etc.

Syntax:

html

{{ value | number:'pattern' }}

The pattern can specify digits and separators.

Example:

html

{{ 12345.6789 | number:'1.2-2' }} <!-- Output: 12,345.68 -->

Explanation:

1 : Minimum number of digits before the decimal point.

2-2 : Minimum and maximum number of decimal places.

Task - Pound to Kg Converter Using Number Pipe


A task like converting pounds to kilograms and formatting the result can be handled with Angular's
number pipe.

Example:

html

<input type="number" [(ngModel)]="pounds" placeholder="Enter pounds" />


<p>{{ pounds * 0.453592 | number:'1.2-2' }} kg</p>

This will display the weight in kilograms, rounded to two decimal places.

Understanding the JSON Pipe

304/411
The JSON Pipe is used to display an object or an array as a JSON-formatted string.

Example:

html

<pre>{{ data | json }}</pre>

This will convert the data object or array into a readable JSON string format and display it.

Displaying Table Data to JSON String


If you have a table of data and you want to display it as a JSON string, you can use the json pipe.

Example:

html

<table>
<tr *ngFor="let row of rows">
<td>{{ row | json }}</td>
</tr>
</table>

This will display each row in JSON format inside the table cells.

Class Decorators @NgModule


03:40
Class Decorators - @Component Decorator
02:55
Property Decorators - @Input() decorator
03:35
IQ - @Input() decorator
01:46
Task - @Input() Decorator
03:22
Property Decorators - @Output decorator
04:29
IQ - @Output decorator
00:53
Task - Using @Input and @Output Together
07:31
Property Decorators - Accessing Child Components With
@ViewChild
08:19

305/411
IQ - @ViewChild decorator
00:56
Property Decorators - Accessing The Projected Content With
@ContentChild
04:07
IQ - @ContentChild() Decorator
01:04
Property Decorators - Binding Properties With @HostBinding
04:16
Method Decorators - Binding Methods To Events With
@HostListener
05:07
Task - Implementing Color Picker
05:29
Parameter Decorators

Class Decorators in Angular

@NgModule Decorator

The @NgModule decorator is used to define an Angular module. It encapsulates a collection of


components, directives, pipes, and services into a cohesive block, making it possible to organize the
application logically.

Example of usage:

typescript

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

declarations : Components, directives, and pipes belonging to this module.

imports : Other modules whose exported classes are needed in this module.

providers : Services that this module provides.

bootstrap : Root component for the application.

@Component Decorator

306/411
The @Component decorator is used to define metadata for a component in Angular. It specifies
properties like the selector, template, and styles for the component.

Example of usage:

typescript

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular App';
}

selector : The tag name used to reference the component.

templateUrl : Path to the HTML template file.

styleUrls : Array of styles to apply to the component.

Property Decorators in Angular

@Input() Decorator

The @Input() decorator allows data to be passed from a parent component to a child component. It is
used to bind a value to a property in the child component.

Example of usage:

typescript

import { Component, Input } from '@angular/core';

@Component({
selector: 'app-child',
template: `<h1>{{ childData }}</h1>`
})
export class ChildComponent {
@Input() childData: string = '';
}

307/411
In the parent component:

html

<app-child [childData]="parentData"></app-child>

Task - @Input() Decorator

You can use the @Input() decorator to pass data from a parent to a child component, creating
dynamic and reusable components. The example above demonstrates this flow.

@Output() Decorator

The @Output() decorator is used to create an event that allows the child component to communicate
with the parent component. It emits an event that the parent component can listen to.

Example of usage:

typescript

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();

sendMessage() {
this.messageEvent.emit('Hello Parent!');
}
}

In the parent component:

html

<app-child (messageEvent)="receiveMessage($event)"></app-child>

Task - Using @Input and @Output Together

You can combine both @Input() and @Output() decorators to create communication between parent
and child components. This can be done by passing data to the child component with @Input() and
receiving events from the child with @Output() .

308/411
@ViewChild Decorator

The @ViewChild decorator is used to access a child component, directive, or DOM element in the
parent component class. It allows you to interact with the child component directly, access its
properties, and call methods.

Example:

typescript

import { Component, ViewChild } from '@angular/core';


import { ChildComponent } from './child/child.component';

@Component({
selector: 'app-parent',
template: `<app-child></app-child>`
})
export class ParentComponent {
@ViewChild(ChildComponent) child: ChildComponent;

ngAfterViewInit() {
console.log(this.child.someMethod());
}
}

@ContentChild Decorator

The @ContentChild() decorator is used to access projected content in a component. It allows you to
retrieve content that is inserted into the component via <ng-content> .

Example:

typescript

@Component({
selector: 'app-content-child',
template: '<ng-content></ng-content>'
})
export class ContentChildComponent {
@ContentChild('content') content: ElementRef;

ngAfterContentInit() {
console.log(this.content.nativeElement);
}
}

309/411
@HostBinding Decorator

The @HostBinding decorator is used to bind a property of the host element to a property of the
component. This can be useful for controlling styles, attributes, or properties directly from within the
component class.

Example:

typescript

import { Component, HostBinding } from '@angular/core';

@Component({
selector: 'app-host-binding',
template: `<p>Host Binding Example</p>`
})
export class HostBindingComponent {
@HostBinding('class.active') isActive = true;
}

@HostListener Decorator

The @HostListener decorator is used to listen for events on the host element and bind them to
methods in the component.

Example:

typescript

import { Component, HostListener } from '@angular/core';

@Component({
selector: 'app-host-listener',
template: `<p>Host Listener Example</p>`
})
export class HostListenerComponent {
@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('Element clicked', event);
}
}

Implementing Color Picker

310/411
In the task of implementing a color picker, you would typically use a form input field with type color ,
and bind it to a component's property using two-way data binding:

html

<input type="color" [(ngModel)]="selectedColor" />


<p>You selected: {{ selectedColor }}</p>

This allows users to pick a color, which will be reflected in the component.

Parameter Decorators
Parameter decorators are used to modify the behavior of method parameters. For example,
@Inject() is used to inject dependencies into a method parameter, while @Optional() is used to
mark a parameter as optional in dependency injection.

These decorators are typically used in service classes or component methods to configure
dependencies or behavior at runtime.

Task - Creating Custom Pipe For Sorting Numbers


06:23
Task - Creating Custom Pipe For Letter Count
03:19
Pure Vs Impure Pipe
03:56
Using Impure Pipes

Task - Creating Custom Pipe for Sorting Numbers


In Angular, you can create a custom pipe to sort an array of numbers. A custom pipe is a class that
implements the PipeTransform interface, allowing you to define your own transformation logic.

Example: Creating a pipe to sort an array of numbers:

1. Generate the pipe:

bash

ng generate pipe sortNumbers

2. Pipe implementation:

typescript

311/411
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'sortNumbers'
})
export class SortNumbersPipe implements PipeTransform {
transform(value: number[], order: string = 'asc'): number[] {
if (!Array.isArray(value)) return value;
return value.sort((a, b) => (order === 'asc' ? a - b : b - a));
}
}

In the above example, the pipe sorts an array of numbers in ascending ( 'asc' ) or descending
( 'desc' ) order based on the input parameter order .

3. Using the pipe in your template:

html

<ul>
<li *ngFor="let num of numbers | sortNumbers:'desc'">{{ num }}</li>
</ul>

Task - Creating Custom Pipe for Letter Count


Another example of a custom pipe is to count the number of letters (or characters) in a given string.

1. Generate the pipe:

bash

ng generate pipe letterCount

2. Pipe implementation:

typescript

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'letterCount'
})

312/411
export class LetterCountPipe implements PipeTransform {
transform(value: string): number {
return value ? value.length : 0;
}
}

This pipe simply returns the number of characters in a given string.

3. Using the pipe in your template:

html

<p>Letter Count: {{ 'Hello World' | letterCount }}</p>

Pure vs Impure Pipes


Pure Pipes:

Pure pipes are those whose output depends only on the input values and will only re-execute
if the inputs to the pipe change. Angular executes pure pipes only when Angular detects a
change in the input data. They are efficient because Angular can cache their output when
inputs stay the same.

Impure Pipes:

Impure pipes are executed on every change detection cycle, even if the input data hasn't
changed. They are useful when dealing with objects like arrays or collections where the data
may change, but the reference of the object may not change.

You can make a pipe impure by setting the pure property to false in the pipe decorator.

Example of pure pipe:

typescript

@Pipe({
name: 'purePipe',
pure: true // This is the default behavior
})
export class PurePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}

313/411
Example of impure pipe:

typescript

@Pipe({
name: 'impurePipe',
pure: false // This makes it an impure pipe
})
export class ImpurePipe implements PipeTransform {
transform(value: any): any {
return value.map(item => item.toUpperCase());
}
}

Using Impure Pipes


Impure pipes are executed more frequently because they run on every change detection cycle. They
are useful in cases where you need to react to data changes, even if the object reference doesn't
change. For example, if you have an array of data that gets modified, and you want the pipe to reflect
those changes, an impure pipe will help.

However, using impure pipes can negatively impact performance, especially for large datasets. It's a
good practice to use them sparingly and only when necessary.

Example of using an impure pipe:

html

<ul>
<li *ngFor="let item of items | impurePipe">{{ item }}</li>
</ul>

In this case, impurePipe will be invoked on every change detection cycle, even if the array items
hasn't changed in terms of object reference.

In summary:

Pure pipes are efficient and only run when input data changes.

Impure pipes are less efficient because they run on every change detection cycle, but they are
necessary when the data structure can change without changing the reference.

314/411
Q - Introduction to Services
01:07
Dependency Injection
03:39
IQ - Dependency Injection
00:44
Providing Services
05:34
IQ - Providing Services
01:42
Injecting services using inject()
06:19
IQ - inject() function

Introduction to Services in Angular


In Angular, services are used to share data and logic across multiple components in an application.
They help with code reusability, separation of concerns, and centralizing business logic or functionality
that can be used by multiple parts of your application. Services are typically implemented as classes
that can be injected into components, directives, or other services.

A service can handle tasks like:

Making HTTP requests

Managing state or data

Performing business logic

Managing application-wide settings

Example of creating a service:

bash

ng generate service my-service

The service class might look like this:

typescript

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root' // This makes the service available globally
})
export class MyService {
constructor() { }

315/411
getGreeting(): string {
return "Hello from MyService!";
}
}

Dependency Injection (DI)


Dependency Injection is a design pattern used in Angular to manage how services and other
dependencies are provided to components and other services. It allows you to inject dependencies (like
services) into classes, making it easy to manage and test your application.

How DI works in Angular:

1. Providers: When you configure Angular to use a service, you are defining a provider that tells
Angular how to create and inject the service.

2. Injector: Angular has an injector that is responsible for instantiating and providing the correct
services when required.

Example of injecting a service into a component:

typescript

import { Component, OnInit } from '@angular/core';


import { MyService } from './my-service.service';

@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent implements OnInit {

constructor(private myService: MyService) { }

ngOnInit(): void {
console.log(this.myService.getGreeting());
}
}

Providing Services

316/411
In Angular, you can provide services in different ways:

1. At the Component Level: A service can be provided only to a component and its children by using
the providers array in the @Component decorator.

typescript

@Component({
selector: 'app-child',
providers: [MyService] // MyService is available only in this component and its
children
})
export class ChildComponent {
constructor(private myService: MyService) { }
}

2. At the Module Level: A service can be provided at the module level, making it available to all
components in that module.

typescript

@NgModule({
providers: [MyService] // MyService is available throughout this module
})
export class AppModule { }

3. Global Scope: You can make a service available globally by providing it in the root using
providedIn: 'root' in the @Injectable decorator. This makes the service available throughout
the application without needing to provide it in every component or module.

Injecting Services using inject()


The inject() function is a new way to inject dependencies into a service or component in Angular. It's
part of Angular's standalone components and constructor-less DI system. It is primarily used in
standalone functions and services where constructor-based DI might not be applicable.

Example of using inject() :

typescript

import { inject } from '@angular/core';


import { MyService } from './my-service.service';

export class MyComponent {

317/411
private myService = inject(MyService);

constructor() {
console.log(this.myService.getGreeting());
}
}

This approach works well with standalone components and functions in Angular, where traditional
constructor injection isn't available or appropriate.

Key Points to Remember:


Services in Angular are used for logic and data management across components.

Dependency Injection (DI) helps Angular manage the dependencies of components and services.

Providing Services can be done at the component, module, or global level using providedIn:
'root' .

The inject() function is an alternative to constructor-based DI, primarily for standalone


components or functions.

These concepts allow for clean, modular, and testable code in Angular applications.

Injecting Tokens
04:25
IQ - Injecting tokens
01:33
Injecting String Tokens
02:23
IQ - Injecting String Tokens
00:42
Injection Token Object
02:44
IQ - Injection Token Object
00:57
Providing Value With useValue
02:12
IQ - Providing Value With useValue
00:35
Task - Provide A Constant Value As Dependency
02:44
Alias Provider - useExisting Property
02:13

318/411
IQ - useExisting Property
00:25
Factory Provider - useFactory Property
02:22
IQ - useFactory Property
01:16
Providing dependencies using “deps” property with useFactory
03:51
IQ - Providing dependencies using “deps” property with useFactory
00:59
useFactory Vs useValue

Injecting Tokens in Angular


In Angular, Injection Tokens are a way to provide and inject dependencies that don't have a specific
type. They are used when you need to inject non-class dependencies such as strings, objects, or other
non-type-based data.

Angular's DI system works based on tokens, which are typically the class names. However, for non-
class types (like string literals, constants, or other objects), you need to create injection tokens.

Injection Token is defined using the InjectionToken class, which creates a unique token for
dependency injection.

Example of creating and using an Injection Token:

typescript

import { InjectionToken } from '@angular/core';

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
providedIn: 'root',
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {}

getData() {
console.log(`API URL: ${this.apiUrl}`);
}
}

Then, provide the value using the token:

typescript

@NgModule({
providers: [

319/411
{ provide: API_URL, useValue: 'https://api.example.com' }
]
})
export class AppModule { }

Injecting String Tokens


String tokens are a special case of tokens where the dependency is represented by a string value rather
than a class or object. You can use string tokens to inject simple values like URLs, API keys, or
configuration settings.

Example of creating and using a string token:

typescript

export const APP_TITLE = new InjectionToken<string>('appTitle');

@Injectable({
providedIn: 'root',
})
export class TitleService {
constructor(@Inject(APP_TITLE) private title: string) {}

getTitle() {
return this.title;
}
}

Providing the value:

typescript

@NgModule({
providers: [
{ provide: APP_TITLE, useValue: 'My Angular Application' }
]
})
export class AppModule { }

Injection Token Object

320/411
An Injection Token Object is typically used when you need to inject an object as a dependency. This is
especially useful for complex configuration settings.

Example:

typescript

export interface Config {


apiEndpoint: string;
enableLogging: boolean;
}

export const CONFIG_TOKEN = new InjectionToken<Config>('configToken');

@Injectable({
providedIn: 'root',
})
export class ConfigService {
constructor(@Inject(CONFIG_TOKEN) private config: Config) {}

getConfig() {
return this.config;
}
}

@NgModule({
providers: [
{ provide: CONFIG_TOKEN, useValue: { apiEndpoint: 'https://api.example.com',
enableLogging: true } }
]
})
export class AppModule { }

Providing Value with useValue


The useValue property allows you to provide a fixed value as a dependency. This is used when you
need to inject a constant, string, or any value directly into the DI system.

Example:

typescript

@NgModule({
providers: [

321/411
{ provide: API_URL, useValue: 'https://api.example.com' }
]
})
export class AppModule { }

This method is useful for values that don't change or are static.

Alias Provider - useExisting Property


The useExisting provider allows you to create an alias for a service, essentially reusing another
service as the dependency.

Example:

typescript

@Injectable({
providedIn: 'root'
})
export class MyService {
getServiceName() {
return 'MyService';
}
}

@Injectable({
providedIn: 'root',
useExisting: MyService // Aliasing another service
})
export class AliasService {
constructor(private myService: MyService) {}

getServiceName() {
return this.myService.getServiceName();
}
}

Factory Provider - useFactory Property

322/411
With useFactory , Angular allows you to provide dependencies based on a factory function. This is
particularly useful when you need to dynamically decide how to provide a service or value based on
runtime conditions.

Example of using a factory function:

typescript

export function apiServiceFactory() {


return new ApiService('https://api.example.com');
}

@NgModule({
providers: [
{ provide: ApiService, useFactory: apiServiceFactory }
]
})
export class AppModule { }

Providing Dependencies Using deps Property with useFactory


You can provide dependencies dynamically in a factory function using the deps property. This allows
you to pass constructor parameters into the factory method.

Example:

typescript

export function myFactory(param: string) {


return new MyService(param);
}

@NgModule({
providers: [
{ provide: MyService, useFactory: myFactory, deps: [API_URL] }
]
})
export class AppModule { }

In this case, the factory function receives the API_URL as a parameter from the DI system and creates
the service dynamically.

323/411
useFactory vs useValue

useValue is used when you want to inject a constant value.

useFactory is used when you need to create a value or service dynamically based on certain
conditions or logic.

Example:

useValue is good for static values.

useFactory is more flexible and allows you to generate values or services on the fly, based on
runtime logic.

Both are essential for providing different kinds of dependencies and values in Angular's DI system.

Introduction To Angular Forms


02:36
Getting Started with Template-Driven Forms: ngForm directive
04:13
IQ - ngForm directive
00:59
Task - Creating A Simple Submit And Reset Form
04:17
Template Driven Form
04:46
IQ - Template Driven Form

Introduction to Angular Forms


Angular provides two main approaches to handle forms: Template-driven forms and Reactive forms.
Template-driven forms are simpler to implement and work primarily through directives in the
template, while Reactive forms provide more control and are more suitable for complex forms.

In template-driven forms, the form controls are defined in the HTML template and are linked to the
Angular form model using directives. Template-driven forms are simple, declarative, and easy to
implement for basic form scenarios.

Getting Started with Template-Driven Forms: ngForm directive


To use template-driven forms in Angular, you first need to import FormsModule from @angular/forms
in your app module.

typescript

324/411
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import FormsModule

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule], // Add FormsModule to imports
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}

In your template, you can use the ngForm directive to initialize the form. It helps bind the form data
with the form controls, making it possible to track the validity and status of the form.

Example of using ngForm directive in a template:

html

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">


<label for="username">Username:</label>
<input type="text" id="username" name="username" ngModel required />

<button type="submit" [disabled]="!myForm.valid">Submit</button>


</form>

In the above example:

ngModel directive binds the input field to the form control.

ngForm creates a form model to keep track of the state of the form.

(ngSubmit) binds the form submission event to the onSubmit() method.

IQ - ngForm directive
The ngForm directive is automatically applied to the form element in template-driven forms. It is
responsible for keeping track of the overall state of the form, such as whether it's valid or dirty, and for
managing its submission.

Key aspects of ngForm:

Tracks the state of the form.

Binds form data with the UI and provides the form status (valid, dirty, etc.).

325/411
Automatically handles validation and submission.

Task - Creating a Simple Submit and Reset Form


A simple form in Angular can use the ngForm directive along with other form control directives like
ngModel to handle form submission and reset functionality.

Example of a simple form with submit and reset:

html

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">


<label for="username">Username:</label>
<input type="text" id="username" name="username" ngModel required />

<button type="submit" [disabled]="!myForm.valid">Submit</button>


<button type="button" (click)="onReset(myForm)">Reset</button>
</form>

Component class:

typescript

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
onSubmit(form: any) {
console.log(form.value); // Form data
}

onReset(form: any) {
form.reset(); // Reset form data
}
}

In this example:

The Submit button triggers the onSubmit() method when clicked, which logs the form data.

The Reset button triggers the onReset() method, which resets the form values.

326/411
Template Driven Form
In template-driven forms, you handle user input and validation directly in the template using directives
like ngModel , ngForm , and required . It is great for simpler forms with less complex logic. You don't
have to write much code in the component class, which makes it very easy to use for simple forms.

IQ - Template Driven Form


Template-driven forms are ideal when:

You are building simple forms with minimal logic.

The form is mostly static with minimal interactivity.

You want to work with Angular's form system declaratively (directly in the template).

You don't need extensive control over the form structure or behavior programmatically.

In such cases, template-driven forms are easy to implement and use, but for more complex forms or
dynamic form controls, reactive forms might be a better option.

Understanding ReactiveFormsModule
02:41
IQ - ReactiveFormsModule
00:54
Understanding FormControl
05:01
IQ - FormControl
01:16
Understanding FormGroup
05:50
IQ - Understanding FormGroup
01:28
Dynamic Forms With FormArray
05:40
IQ - Dynamic Forms With FormArray
01:22
Understanding FormBuilder
01:52
IQ - FormBuilder
00:37
Validating Form Controls
05:31

327/411
IQ - Validating Form Controls
00:31
Task - Creating Multi Step Reactive Form With Bootstrap (Part 1)
05:02
Task - Creating Multi Step Reactive Form With Bootstrap (Part 2)
03:56
Task - Creating Multi Step Reactive Form With Bootstrap (Part 3)
08:25
Tracking Form Control States
04:34
IQ - Tracking Form Control States
00:44
Task - Multiple Validations On Password Field
04:52
Creating Custom Validators
05:02
IQ - Creating Custom Validators
00:51
Task - Custom URL Validator
05:56
Securing Routes With Route Guards
06:05
IQ - Route Guards
01:12
CanDeactivate Route Guard
06:37
IQ - CanDeactivate Route Guard
00:49
CanActivateChild Route Guard
05:11
IQ - CanActivateChild Route Guard
00:24
Task - Login Authentication
07:21
CanMatch Guard
05:03
IQ - CanMatch Guard
01:03

Understanding ReactiveFormsModule
In Angular, Reactive Forms (also known as Model-Driven Forms) offer more control and flexibility over
the form logic than Template-Driven Forms. To use reactive forms in Angular, the
ReactiveFormsModule needs to be imported into your module.

1. ReactiveFormsModule helps create forms programmatically in the component class.

2. It provides an easier way to track form state and validation programmatically.

328/411
3. Reactive forms are more scalable for complex forms because they offer explicit control over form
data and validation.

To use reactive forms, import ReactiveFormsModule in your app module:

typescript

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [ReactiveFormsModule],
// other properties
})
export class AppModule {}

IQ - ReactiveFormsModule
Reactive forms are ideal when you need:

More control over the form, including dynamic validation.

Complex form scenarios such as conditional validation, complex logic, and asynchronous
operations.

A programmatic approach where form models are defined and controlled in the component.

Understanding FormControl
A FormControl represents an individual input element in a form. It tracks the value, validation, and
status of that input.

Example:

typescript

import { FormControl } from '@angular/forms';

const name = new FormControl(''); // Initial value is an empty string

You can set validators or asynchronous validators on the FormControl :

typescript

329/411
name.setValidators([Validators.required, Validators.minLength(3)]);

IQ - FormControl
A FormControl is primarily used for:

Tracking the value of form inputs.

Applying validation and tracking the status (valid, invalid, dirty, touched).

Setting or updating the form input value programmatically.

Understanding FormGroup
A FormGroup is used to group multiple FormControl instances into a single object. It's typically used
to represent a logical group of related form controls.

Example:

typescript

import { FormGroup, FormControl } from '@angular/forms';

const formGroup = new FormGroup({


name: new FormControl(''),
email: new FormControl(''),
});

A FormGroup also allows you to apply validation across multiple form controls and track their status
collectively.

IQ - Understanding FormGroup
A FormGroup is useful when:

You want to organize related form controls together.

You need to apply shared validation across multiple controls (e.g., both name and email fields
must be required).

330/411
You need to manage the state of a group of related inputs.

Dynamic Forms With FormArray


A FormArray allows you to manage an array of form controls dynamically. This is useful when you have
a collection of similar fields, such as a list of user emails or phone numbers.

Example:

typescript

import { FormArray, FormControl } from '@angular/forms';

const emails = new FormArray([


new FormControl(''),
new FormControl('')
]);

You can dynamically add or remove form controls from a FormArray :

typescript

emails.push(new FormControl(''));
emails.removeAt(0);

IQ - Dynamic Forms With FormArray


A FormArray is beneficial when:

You don't know in advance how many form controls you need (e.g., a dynamic list of items).

You want to perform operations like adding, removing, or updating form controls dynamically.

Understanding FormBuilder
The FormBuilder service is a convenience service provided by Angular to simplify the creation of form
controls, form groups, and form arrays. It helps reduce boilerplate code when defining reactive forms.

Example:

331/411
typescript

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

constructor(private fb: FormBuilder) {}

createForm() {
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}

IQ - FormBuilder
FormBuilder is useful when:

You want to simplify the process of creating form controls and groups.

You want to avoid manually instantiating FormGroup and FormControl .

You prefer a cleaner and more readable way to define forms.

Validating Form Controls


Angular provides various built-in validators like required , minLength , maxLength , pattern , and
custom validators for form controls. You can apply validation both synchronously and asynchronously.

Example:

typescript

name.setValidators([Validators.required, Validators.minLength(3)]);

You can check if a control is valid using:

typescript

this.form.get('name').valid;

332/411
IQ - Validating Form Controls
Form controls are validated when:

They lose focus ( blur event).

You call markAsTouched() or markAsDirty() .

You check the control’s validity programmatically.

Task - Creating Multi Step Reactive Form With Bootstrap


A multi-step form involves breaking down a single long form into multiple sections, each with its own
form controls. This can be achieved using Angular’s reactive forms by creating multiple FormGroup
instances, one for each step.

Example steps:

1. Define different FormGroup instances for each step.

2. Bind them to separate sections in the HTML.

3. Use the next and previous buttons to navigate between the steps.

This allows for a more user-friendly approach when dealing with large forms.

Tracking Form Control States


You can track the state of a form control by using properties like valid , invalid , pristine , dirty ,
touched , and untouched . These properties help in managing the form’s user interaction state.

Example:

typescript

this.form.get('name').valid; // Returns true/false based on validity


this.form.get('name').dirty; // Returns true if value has been changed

IQ - Tracking Form Control States


Form control states help in:

333/411
Providing feedback to users (e.g., showing error messages if a field is invalid).

Enabling or disabling buttons based on the form's validity.

Determining if the user has interacted with the form (e.g., marking a field as touched after focus
loss).

Creating Custom Validators


Custom validators allow you to create validation logic tailored to your specific needs.

Example:

typescript

import { AbstractControl, ValidationErrors } from '@angular/forms';

export function customValidator(control: AbstractControl): ValidationErrors | null {


return control.value && control.value.includes('test') ? { invalidTest: true } : null;
}

You can apply the custom validator to a form control like so:

typescript

this.form.get('name').setValidators([customValidator]);

IQ - Creating Custom Validators


Custom validators are useful when:

The built-in validators don’t fulfill your specific validation needs.

You need to apply complex validation logic based on multiple fields or external conditions.

Securing Routes With Route Guards


Route guards in Angular help prevent unauthorized access to specific routes. Guards can be used to:

Protect routes from unauthorized users.

334/411
Handle actions before navigation like checking if the user is logged in.

Types of route guards:

CanActivate : Prevents or allows access to a route.

CanActivateChild : Protects child routes.

CanDeactivate : Prevents leaving a route when changes are unsaved.

IQ - Route Guards
Route guards help:

Ensure only authorized users can access certain routes.

Prevent navigation when certain conditions aren't met (e.g., unsaved changes).

CanDeactivate Route Guard


CanDeactivate guards help prevent the user from leaving a page when there are unsaved changes.
It's typically used for forms where you need to confirm if the user wants to leave without saving.

IQ - CanDeactivate Route Guard


CanDeactivate is useful when:

You want to warn users before they leave a page with unsaved changes.

You need to prompt users for confirmation before navigating away from the current route.

CanActivateChild Route Guard


CanActivateChild is used to guard child routes, ensuring that only authorized users can access the
child routes.

335/411
IQ - CanActivateChild Route Guard
This guard is useful when:

You need to protect child routes based on certain conditions.

You want to ensure that access to nested routes is controlled by a parent route guard.

Task - Login Authentication


In this task, you would implement a login form and authenticate users before allowing them access to
protected routes. This typically involves:

Using route guards ( CanActivate ) to protect routes.

Implementing authentication logic in a service.

CanMatch Guard
The CanMatch guard can be used to determine if a route should be matched based on custom
conditions, such as user roles or permissions.

IQ - CanMatch Guard
The CanMatch guard is beneficial when:

You want to apply custom logic for route matching.

You need to apply different matching strategies based on user roles, URL segments, or other
factors.

Understanding ReactiveFormsModule
In Angular, reactive forms allow you to work with forms in a more programmatic way, giving you more
control over form data, validation, and handling form states. To use reactive forms in Angular, you need
to import the ReactiveFormsModule into your application module.

Steps to Use Reactive Forms:

1. Import ReactiveFormsModule:

typescript

336/411
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [ReactiveFormsModule],
// other properties
})
export class AppModule {}

2. Define the form model: You define the form controls and groups in the component class.

3. Bind the form model to HTML: You bind the form controls to your template using form control
directives.

Reactive forms are ideal when you need more control over the form's structure and logic, such as
dynamic validation or form arrays.

IQ - ReactiveFormsModule
Reactive forms are recommended when:

Dynamic forms: You need to create forms based on dynamic data (e.g., form arrays for repeated
fields).

Advanced validation logic: You require complex validation rules that can be applied
programmatically.

Fine-grained control: You want to programmatically interact with the form controls (e.g., changing
values, validation, etc.).

Understanding FormControl
A FormControl is a class in Angular's reactive form module that represents a single input field in a
form. It holds the value, status (valid, invalid), and validation errors of an individual form control.

Basic Usage:

typescript

import { FormControl } from '@angular/forms';

// Creating a new form control with an initial value

337/411
const name = new FormControl('');

// Adding validation to a form control


name.setValidators([Validators.required, Validators.minLength(3)]);

Properties and Methods of FormControl:

value: The current value of the form control.

valid/invalid: The validity of the control based on the defined validators.

touched/untouched: Tracks whether the control has been interacted with.

dirty/pristine: Tracks whether the user has changed the value.

IQ - FormControl
A FormControl is a great choice when:

You need to work with an individual form field in isolation.

You want to manage the value, validation, and state of a single field without dealing with complex
groupings.

Understanding FormGroup
A FormGroup is used to group related form controls into a single unit. It represents a collection of
FormControl s and allows for managing validation and form state for multiple controls as a group.

Example of FormGroup:

typescript

import { FormGroup, FormControl } from '@angular/forms';

const formGroup = new FormGroup({


name: new FormControl(''),
email: new FormControl(''),
});

In the example above, a FormGroup is created with two form controls, one for name and one for
email . You can perform validation on the entire group, and the status of the group will reflect the
validation of all controls.

338/411
IQ - Understanding FormGroup
A FormGroup is useful when:

You need to group related form fields together (e.g., a name, email, and phone fields).

You want to validate a set of controls together or disable/enable a set of controls based on a
condition.

You are working with multi-step forms where each step contains multiple form fields.

Dynamic Forms With FormArray


A FormArray is a special kind of FormGroup used for managing an array of form controls. It’s useful
when you need to dynamically add or remove form controls, such as a list of emails, phone numbers,
or other repeatable fields.

Example of FormArray:

typescript

import { FormArray, FormControl } from '@angular/forms';

const emails = new FormArray([


new FormControl(''),
new FormControl(''),
]);

// Dynamically add more controls


emails.push(new FormControl(''));

// Dynamically remove a control


emails.removeAt(0);

IQ - Dynamic Forms With FormArray


A FormArray is beneficial when:

You have an unknown number of form fields that need to be dynamically generated.

You want to enable the user to add/remove items from a list of controls.

339/411
Understanding FormBuilder
The FormBuilder service in Angular is a helper service to simplify the process of creating form controls
and groups. It eliminates the need to manually instantiate FormControl or FormGroup .

Example Using FormBuilder:

typescript

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

constructor(private fb: FormBuilder) {}

createForm() {
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}

In the example above, FormBuilder creates the FormGroup and FormControl for the name and
email fields with validation.

IQ - FormBuilder
FormBuilder is great when:

You want to reduce boilerplate code in your form setup.

You want a cleaner, more readable way to create forms.

You prefer a declarative approach to building forms.

Validating Form Controls


Angular provides both built-in validators (e.g., required , minLength , maxLength , pattern ) and the
ability to create custom validators. Validators are functions that check whether the form control's value
satisfies certain conditions.

Built-in Validators:

340/411
typescript

this.form.get('name').setValidators([Validators.required, Validators.minLength(3)]);

Custom Validators:

typescript

import { AbstractControl, ValidationErrors } from '@angular/forms';

export function customValidator(control: AbstractControl): ValidationErrors | null {


return control.value && control.value.includes('test') ? { invalidTest: true } : null;
}

IQ - Validating Form Controls


Form control states can be tracked using:

valid: True if all validators pass.

invalid: True if any validator fails.

touched: True if the user interacted with the field.

dirty: True if the field value was modified.

Task - Creating Multi Step Reactive Form With Bootstrap


A multi-step form breaks down a long form into multiple sections, each having its own set of fields.
The user progresses through each step sequentially, which improves user experience.

1. Form Setup: Define separate FormGroup instances for each step.

2. Step Navigation: Use navigation buttons ( next and previous ) to allow users to move between
steps.

Tracking Form Control States


Tracking form control states in Angular is crucial for providing real-time feedback to users. For
example, you can display error messages or disable buttons based on the form's validity.

341/411
Common States:

valid: True if the control's value passes all validators.

invalid: True if the control's value fails any validator.

dirty: True if the control's value has been changed.

pristine: True if the control's value has not been changed.

touched: True if the user has focused on the control and then blurred it.

Example:

typescript

if (this.form.get('name').invalid) {
// Show error message
}

IQ - Tracking Form Control States


Form control states help:

Enable/Disable Actions: You can enable or disable form submission based on the form’s validity
( this.form.valid ).

Feedback: Show validation messages when the form control state changes (e.g., error messages
when invalid).

Creating Custom Validators


Custom validators allow you to define your own validation logic for form controls. They are useful
when the built-in validators don't meet your needs.

Example of a Custom Validator:

typescript

import { AbstractControl, ValidationErrors } from '@angular/forms';

export function noSpaceValidator(control: AbstractControl): ValidationErrors | null {


return control.value && control.value.indexOf(' ') !== -1 ? { noSpace: true } : null;
}

342/411
Using Custom Validators:

typescript

this.form.get('username').setValidators([noSpaceValidator]);

IQ - Creating Custom Validators


Custom validators are useful when:

You need validation logic that is not covered by Angular’s built-in validators.

You need to validate form controls based on complex conditions (e.g., multiple field comparisons
or external data).

Securing Routes With Route Guards


Route guards are a way to prevent unauthorized users from accessing certain routes in your Angular
application. They allow you to protect routes by checking if the user has the required permissions or if
certain conditions are met before allowing navigation.

Types of Route Guards:

CanActivate: Prevents or allows navigation to a route.

CanActivateChild: Prevents or allows navigation to child routes.

CanDeactivate: Prevents users from leaving a route if there are unsaved changes.

CanMatch: Used to conditionally match routes based on custom logic.

IQ - Route Guards
Route guards are essential when:

You want to protect routes from unauthorized access.

You need to confirm a user’s actions before allowing them to leave a page (e.g., unsaved changes).

343/411
CanDeactivate Route Guard
A CanDeactivate guard helps prevent users from navigating away from a route when there are
unsaved changes, such as form data.

Example of CanDeactivate Guard:

typescript

import { Injectable } from '@angular/core';


import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';

export interface CanComponentDeactivate {


canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable({
providedIn: 'root'
})
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> |
boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}

IQ - CanDeactivate Route Guard


Use CanDeactivate when:

You want to warn users about unsaved changes.

You need to confirm navigation away from a page to prevent data loss.

Introduction To Lazy Loading


01:50
Lazy Loading Of Components
06:46
Preloading of Components
05:10
IQ - Preloading of Components

344/411
01:29
Preloading Strategy (NoPreloading)
02:51
IQ - NoPreloading Strategy
00:28
Preloading Strategy (Custom Preloading)
06:01
IQ - Custom Preloading Strategy
01:30
Task - Preloading Based On User Roles
02:35
IQ - Preloading Vs. Lazy Loading
01:45
Deferred Loading
05:22
@defer with @placeholder
02:56
@defer with @loading
02:27
@defer with @error
01:27
Working with Triggers (on idle)
02:49
Working with Triggers (on viewport)
04:44
Working with Triggers (on interaction)
01:31
Working with Triggers (on hover)
02:01
Working with Triggers (on immediate)
01:07
Working with Triggers (on timer)
01:07
Prefetching of @defer blocks
02:05
Defining Custom Triggers
explain in detail with examples

Introduction to Lazy Loading


Lazy loading is a design pattern in Angular used to load modules only when they are required, rather
than loading all of them upfront. This improves the application’s initial loading time and reduces the
bundle size by splitting the application into smaller chunks that are loaded on demand. Angular
provides a powerful mechanism to implement lazy loading using the Router.

Advantages of Lazy Loading:

345/411
Faster Initial Load: By loading only the essential parts of an app initially, lazy loading reduces the
time taken to load the app.

Better Performance: Resources like scripts and styles are loaded only when needed, saving
bandwidth and improving performance.

Separation of Concerns: Lazy loading enables a clear separation between modules in the app,
ensuring that only the required modules are loaded, rather than everything at once.

Lazy Loading of Components


Lazy loading in Angular is typically done at the module level, but it can also be applied to specific
components. For a component to be lazy-loaded, it needs to be declared inside a feature module and
then the module itself must be lazy-loaded.

Example:

Let’s say you have a component called DashboardComponent and a module called DashboardModule .
Instead of loading the DashboardModule with the app’s initial load, you can lazy-load it when the user
navigates to the dashboard route.

1. Create a Feature Module ( dashboard.module.ts ):

typescript

@NgModule({
declarations: [DashboardComponent],
imports: [CommonModule],
})
export class DashboardModule {}

2. Define Lazy Loading in the Routing Module ( app-routing.module.ts ):

typescript

const routes: Routes = [


{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m =>
m.DashboardModule) },
];

In this example, the DashboardModule is loaded lazily when the user navigates to the /dashboard
route.

346/411
Preloading of Components
Preloading is the process of loading modules in the background after the initial app load, but before
the user navigates to the route. It’s used to improve the user experience by loading modules that the
user may likely navigate to next, without waiting for the user to explicitly trigger the loading.

Preloading Strategy:

Angular provides a default no preloading strategy and the option for custom preloading strategies to
allow loading modules in the background.

Preloading Strategy (NoPreloading)


By default, Angular uses the NoPreloading strategy. This means that modules are lazy-loaded only
when they are required by the user. No preloading is done in the background.

typescript

RouterModule.forRoot(routes, { preloadingStrategy: NoPreloading })

This is useful when you want to save bandwidth and only load resources when requested by the user.

Preloading Strategy (Custom Preloading)


A Custom Preloading Strategy allows you to define how and when to preload modules based on your
own conditions. This can be useful when you want to preload certain modules after the app is loaded
or based on certain events.

Example of Custom Preloading Strategy:

Create a custom preloading strategy by implementing PreloadingStrategy :

typescript

import { PreloadingStrategy, Route, Router } from '@angular/router';


import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';

@Injectable({
providedIn: 'root'

347/411
})
export class CustomPreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<any>): Observable<any> {
// Preload if the route's data has a 'preload' flag
return route.data && route.data['preload'] ? load() : of(null);
}
}

Now, apply the custom preloading strategy in the routing module:

typescript

RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })

Add the preload flag to specific routes:

typescript

const routes: Routes = [


{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m =>
m.DashboardModule), data: { preload: true } },
];

With this setup, the DashboardModule will be preloaded in the background if the preload flag is
true .

Task - Preloading Based on User Roles


Preloading can be based on user roles, allowing different user types to have different sets of preloaded
modules. For example, an admin might need certain modules preloaded that regular users do not.

Example of Preloading Based on User Roles:

1. Custom Preloading Strategy:

typescript

@Injectable({
providedIn: 'root'
})
export class RoleBasedPreloadingStrategy implements PreloadingStrategy {
constructor(private authService: AuthService) {}

preload(route: Route, load: () => Observable<any>): Observable<any> {

348/411
if (this.authService.isAdmin() && route.data['preloadForAdmin']) {
return load(); // Preload for admin users
}
return of(null); // Do not preload for other users
}
}

2. Routing Setup:

typescript

const routes: Routes = [


{ path: 'admin-dashboard', loadChildren: () => import('./admin-dashboard/admin-
dashboard.module').then(m => m.AdminDashboardModule), data: { preloadForAdmin: true } },
];

This ensures that admin-specific modules are preloaded while other modules are only loaded when
requested.

Lazy Loading vs Preloading


Lazy Loading: Modules are only loaded when they are needed (e.g., when the user navigates to
that route).

Preloading: Modules are loaded in the background, even before the user navigates to them.

Lazy loading helps reduce the initial load time, while preloading ensures that certain modules are
available without waiting when the user decides to navigate to them.

Deferred Loading
Deferred Loading refers to delaying the loading of resources (e.g., images, modules) until certain
conditions are met. This can be done by using placeholders or loading indicators until the resource is
ready.

Using @defer with @placeholder , @loading , and @error :

@defer: Delays loading until specified.

@placeholder: A temporary placeholder until the content loads.

349/411
@loading: A loading indicator that is displayed until the content is fully loaded.

@error: Handles errors that occur during the loading process.

Example:

html

<img [src]="imageUrl" @defer [placeholder]="'loading.jpg'" [@loading]="loading"


[@error]="error">

In this example, the image will only load when it is needed, showing a loading placeholder initially, and
an error message if it fails to load.

Working with Triggers


Triggers allow deferred or lazy loading of resources based on specific events such as user interaction or
idle time.

Triggers can be based on:

1. Idle Trigger: Waits until the user is idle before triggering loading.

typescript

@defer onIdle

2. Viewport Trigger: Loads resources when they come into view in the viewport.

typescript

@defer onViewport

3. Interaction Trigger: Triggers loading when the user interacts with the page (e.g., clicks a button).

typescript

@defer onInteraction

4. Hover Trigger: Loads when the user hovers over a particular element.

typescript

@defer onHover

5. Immediate Trigger: Immediately triggers loading as soon as the element is available.

350/411
typescript

@defer onImmediate

6. Timer Trigger: Defers loading based on a specific time interval.

typescript

@defer onTimer

Prefetching of @defer Blocks


Prefetching is the act of preloading content before it’s required. Using @defer , you can preload
certain blocks of content ahead of time, so they are immediately available when the user interacts with
them.

typescript

@defer prefetch

This ensures that content that may be needed soon is fetched and ready before the user triggers the
loading.

Defining Custom Triggers


Custom triggers allow you to define your own conditions for when to load resources. You could trigger
based on a specific event or a custom condition you define in your app.

typescript

@defer onCustomTrigger

For instance, you might want to load resources after the user has scrolled a certain distance down the
page. Custom triggers give you full flexibility in how and when to defer loading.

351/411
These techniques improve the user experience and application performance by delaying the loading of
non-essential resources until they are required, ensuring smoother and faster interactions.

Understanding Observables & RxJS


06:16
IQ - Observables & RxJS
01:03
Managing Observables & Subscribers
07:15
IQ - Managing Observables & Subscribers
01:03
Unsubscribing an Observable
04:55
IQ - Unsubscribing an Observable
01:02
Understanding Async Pipe
05:13
IQ - Understanding Async Pipe
00:54
Task - Fetching JSON Data With Async Pipe
04:27
Hot Observable Vs Cold Observable
explain in detail with examples

Understanding Observables & RxJS


Observables are a fundamental concept in RxJS (Reactive Extensions for JavaScript), allowing you to
work with asynchronous data streams. They provide a powerful way to handle events, asynchronous
operations, and streams of data over time, such as user inputs, HTTP requests, or WebSocket
messages.

An Observable is an object that represents a collection of future values or events. You can think of it as
a stream that emits values over time.

Basic Observable Example:

typescript

import { Observable } from 'rxjs';

const observable = new Observable(observer => {


observer.next('Hello');
observer.next('World');
observer.complete();
});

observable.subscribe(value => {

352/411
console.log(value); // Output: Hello World
});

In the above example, the Observable emits two values ( 'Hello' and 'World' ) and completes the
stream.

RxJS (Reactive Extensions for JavaScript) is a library for composing asynchronous and event-based
programs using Observables. It provides a set of operators like map , filter , merge , and many
others that help you manipulate and combine multiple Observables.

Managing Observables & Subscribers


In Angular, Observables are used extensively for handling asynchronous data. You subscribe to an
Observable to receive the emitted values or events.

Managing Subscriptions:

When you subscribe to an Observable, you get a Subscription object. This object allows you to manage
and cancel the subscription (unsubscribe).

typescript

import { Observable } from 'rxjs';

const observable = new Observable(observer => {


observer.next('Hello');
observer.next('World');
observer.complete();
});

const subscription = observable.subscribe(value => {


console.log(value); // Output: Hello World
});

// Unsubscribe from the observable to stop receiving values


subscription.unsubscribe();

If you don't unsubscribe from an Observable, it can lead to memory leaks, as the subscription will
continue to emit values even after the component or service is destroyed.

Unsubscribing an Observable

353/411
Unsubscribing is important in Angular applications to avoid memory leaks. If a component subscribes
to an Observable, it’s necessary to unsubscribe when the component is destroyed.

Unsubscribing using ngOnDestroy :

Angular provides the ngOnDestroy lifecycle hook to clean up subscriptions when a component is
destroyed.

typescript

import { Component, OnDestroy } from '@angular/core';


import { Observable, Subscription } from 'rxjs';

@Component({
selector: 'app-example',
template: `<div>Check console for output</div>`
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;

ngOnInit() {
const observable = new Observable(observer => {
observer.next('Hello');
observer.next('World');
observer.complete();
});

this.subscription = observable.subscribe(value => {


console.log(value);
});
}

ngOnDestroy() {
// Unsubscribe when the component is destroyed to prevent memory leaks
this.subscription.unsubscribe();
}
}

By calling unsubscribe() inside ngOnDestroy , you ensure that the subscription is properly cleaned up
when the component is removed from the DOM.

Understanding Async Pipe

354/411
The async pipe is a powerful feature in Angular used to automatically subscribe and unsubscribe from
Observables in templates. It helps manage Observables without having to manually handle the
subscription and unsubscription in the component class.

Example Using Async Pipe:

html

<!-- Component HTML -->


<div>{{ observableData | async }}</div>

typescript

import { Component } from '@angular/core';


import { Observable, of } from 'rxjs';

@Component({
selector: 'app-example',
template: `<div>{{ observableData | async }}</div>`
})
export class ExampleComponent {
observableData: Observable<string>;

ngOnInit() {
this.observableData = of('Hello, Async Pipe!');
}
}

In this example:

The observableData is an Observable of type string .

The async pipe subscribes to this Observable, automatically updating the view when new values
are emitted.

Angular will handle the subscription and unsubscription for you when the component is destroyed,
so you don't need to manually unsubscribe.

Advantages of Async Pipe:

1. Automatic Subscription/Unsubscription: Automatically subscribes when the component loads


and unsubscribes when it is destroyed.

2. Simplified Code: Reduces the need to manually manage subscriptions, making your code cleaner
and less error-prone.

355/411
Task - Fetching JSON Data With Async Pipe
Fetching data from an API and displaying it in the template using the async pipe is one of the most
common use cases.

typescript

import { Component, OnInit } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
selector: 'app-data-fetch',
template: `
<ul>
<li *ngFor="let item of data$ | async">{{ item.name }}</li>
</ul>
`
})
export class DataFetchComponent implements OnInit {
data$: Observable<any>;

constructor(private http: HttpClient) {}

ngOnInit() {
this.data$ = this.http.get<any[]>('https://api.example.com/data');
}
}

In this example:

The component fetches JSON data from an API using HttpClient .

The data is bound to the template using the async pipe, which automatically subscribes and
updates the view when the data is loaded.

Hot Observable vs Cold Observable


Understanding the difference between Hot and Cold Observables is crucial for working with
Observables in Angular and RxJS.

Cold Observable:

A Cold Observable starts emitting values only when it is subscribed to. Each subscriber gets a separate
execution and independent stream of data. This is ideal for HTTP requests or scenarios where each

356/411
subscriber needs a fresh, separate stream of data.

Example: HTTP requests are Cold Observables. When multiple components subscribe to the same
HTTP request, each component gets a fresh response.

typescript

import { of } from 'rxjs';

const coldObservable = of('Hello', 'World');

coldObservable.subscribe(value => console.log(value)); // Logs: Hello, World


coldObservable.subscribe(value => console.log(value)); // Logs: Hello, World

Here, each subscription triggers the Observable to emit the same values independently.

Hot Observable:

A Hot Observable emits values regardless of whether there are subscribers or not. When a subscriber
joins, it starts receiving the values that have been emitted so far. It is shared between multiple
subscribers, meaning they get the same set of emitted values. Event listeners, WebSocket
connections, and Subject-based Observables are examples of Hot Observables.

Example: A Subject is a Hot Observable. It can multicast values to multiple subscribers without
re-executing the source stream.

typescript

import { Subject } from 'rxjs';

const hotObservable = new Subject();

hotObservable.subscribe(value => console.log(`Subscriber 1: ${value}`));


hotObservable.subscribe(value => console.log(`Subscriber 2: ${value}`));

hotObservable.next('Hello');
hotObservable.next('World');

In this case, both subscribers will receive the same emissions ( 'Hello' and 'World' ), but the
emissions happen independently of the subscriptions.

Summary
Observables are used to represent asynchronous data streams.

357/411
RxJS provides operators to manipulate Observables (e.g., map , filter , merge ).

Async pipe automatically subscribes to and unsubscribes from Observables in Angular templates.

Hot Observables are shared and emit values even if there are no subscribers.

Cold Observables emit values only when subscribed to and provide fresh data to each subscriber.

This fundamental understanding of Observables and RxJS is critical for building reactive, scalable
Angular applications.

RxJS { of } Operator
02:58
IQ - RxJS { of } Operator
00:23
RxJS { from } Operator
01:56
IQ - RxJS { from } Operator
00:59
RxJS { interval } Operator
03:11
RxJS { timer } Operator
03:43
Task - Implementing a loading spinner
03:07
RxJS { EMPTY } Operator
02:38
IQ - RxJS { EMPTY } Operator
00:57
RxJS Pipeable Operators
03:00
IQ - RxJS Pipeable Operators
01:10
RxJS { filter } Operator
03:32
RxJS { map } Operator
04:43
IQ - RxJS { map } Operator
00:44
RxJS { mergeMap } Operator
02:38
IQ - RxJS { mergeMap } Operator
01:17
Task - Displaying the Products Associated With User
02:42
RxJS { concatMap } Operator
03:56
IQ - concatMap() operator

358/411
01:06
RxJS { switchMap } Operator
04:13
IQ - RxJS { switchMap } Operator
explain in detail with examples

RxJS Operators in Detail with Examples


RxJS (Reactive Extensions for JavaScript) provides a wide variety of operators to handle asynchronous
streams and events. These operators can be categorized into different types, such as creation
operators, transformation operators, and combination operators. Below, we’ll dive into several
important RxJS operators with detailed explanations and examples:

1. of Operator
The of operator is used to create an Observable that emits a sequence of values (either from a single
value or an array of values) immediately when subscribed.

Example:

typescript

import { of } from 'rxjs';

const observable = of(1, 2, 3, 4);

observable.subscribe(value => {
console.log(value); // Output: 1, 2, 3, 4
});

Explanation:

The of operator immediately emits the values 1, 2, 3, 4 in order when the subscription
happens.

2. from Operator
The from operator is used to convert different types of data structures into an Observable. It can take
an array, a promise, or an iterable, and emit the values of that structure as a sequence.

Example:

359/411
typescript

import { from } from 'rxjs';

const observable = from([1, 2, 3, 4]);

observable.subscribe(value => {
console.log(value); // Output: 1, 2, 3, 4
});

Explanation:

The from operator converts an array into an Observable and emits each value in the array
sequentially.

3. interval Operator
The interval operator creates an Observable that emits increasing numbers starting from 0 at a
specified interval, indefinitely.

Example:

typescript

import { interval } from 'rxjs';

const observable = interval(1000); // Emits every 1 second

observable.subscribe(value => {
console.log(value); // Output: 0, 1, 2, 3, 4, ...
});

Explanation:

The interval operator emits an increasing sequence of integers starting from 0 at a fixed interval
of 1 second (1000 milliseconds).

4. timer Operator
The timer operator creates an Observable that waits for a specified delay before emitting a single
value or multiple values at regular intervals.

360/411
Example:

typescript

import { timer } from 'rxjs';

const observable = timer(2000, 1000); // First value after 2 seconds, subsequent values every
1 second

observable.subscribe(value => {
console.log(value); // Output: 0, 1, 2, 3, ...
});

Explanation:

The timer operator emits a value after an initial delay of 2 seconds and then continues to emit
values every second thereafter.

5. EMPTY Operator
The EMPTY operator creates an Observable that immediately completes without emitting any values.

Example:

typescript

import { EMPTY } from 'rxjs';

const observable = EMPTY;

observable.subscribe({
next: value => console.log(value), // Nothing will be logged
complete: () => console.log('Completed!') // Output: 'Completed!'
});

Explanation:

The EMPTY operator doesn't emit any values but immediately completes the Observable stream.

**6. RxJS Pipeable Operators

361/411
Pipeable operators are operators that can be chained using the pipe() method on an Observable.
They are used to transform, filter, or manage the data emitted by the Observable.

Example:

typescript

import { of } from 'rxjs';


import { map, filter } from 'rxjs/operators';

const observable = of(1, 2, 3, 4, 5).pipe(


filter(value => value % 2 === 0),
map(value => value * 2)
);

observable.subscribe(value => {
console.log(value); // Output: 4, 8
});

Explanation:

The pipe() method chains the filter() and map() operators:

The filter() operator filters out odd numbers.

The map() operator multiplies the remaining even numbers by 2.

7. filter Operator
The filter operator is used to filter the emitted values based on a condition, similar to the JavaScript
Array.filter() method.

Example:

typescript

import { of } from 'rxjs';


import { filter } from 'rxjs/operators';

const observable = of(1, 2, 3, 4, 5).pipe(


filter(value => value % 2 === 0)
);

observable.subscribe(value => {

362/411
console.log(value); // Output: 2, 4
});

Explanation:

The filter operator only passes through even numbers (i.e., 2, 4).

8. map Operator
The map operator is used to transform the emitted values by applying a given function.

Example:

typescript

import { of } from 'rxjs';


import { map } from 'rxjs/operators';

const observable = of(1, 2, 3).pipe(


map(value => value * 2)
);

observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});

Explanation:

The map operator multiplies each emitted value by 2.

9. mergeMap Operator
The mergeMap operator is used to transform each value emitted by the source Observable into a new
Observable and merge the results into one Observable. The result is emitted as a combined stream.

Example:

typescript

import { of } from 'rxjs';


import { mergeMap } from 'rxjs/operators';

const observable = of(1, 2, 3).pipe(

363/411
mergeMap(value => of(value * 2))
);

observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});

Explanation:

The mergeMap operator takes each value from the source Observable and transforms it into a new
Observable (which is of(value * 2) in this case). It then merges the resulting Observables into
one stream.

10. concatMap Operator


The concatMap operator works similarly to mergeMap , but it ensures that the emitted values are
processed one at a time in the order they are received. If the first Observable hasn't completed, it waits
before processing the next one.

Example:

typescript

import { of } from 'rxjs';


import { concatMap } from 'rxjs/operators';

const observable = of(1, 2, 3).pipe(


concatMap(value => of(value * 2))
);

observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});

Explanation:

Unlike mergeMap , concatMap ensures that the values are emitted sequentially (one after another),
waiting for the completion of the current Observable before starting the next one.

11. switchMap Operator

364/411
The switchMap operator is used to switch to a new Observable based on each value emitted by the
source Observable, canceling the previous subscription if a new value arrives.

Example:

typescript

import { of } from 'rxjs';


import { switchMap } from 'rxjs/operators';

const observable = of(1, 2, 3).pipe(


switchMap(value => of(value * 2))
);

observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});

Explanation:

The switchMap operator maps each emitted value to a new Observable and unsubscribes from
the previous one as soon as a new value arrives.

Task - Implementing a Loading Spinner


In this task, you can use RxJS operators to show a loading spinner while an asynchronous operation
(e.g., fetching data) is in progress.

typescript

import { of, delay } from 'rxjs';


import { switchMap, tap } from 'rxjs/operators';

const fetchData = () => of('Data loaded').pipe(delay(2000));

const observable = of('Loading...').pipe(


tap(() => console.log('Show spinner')),
switchMap(() => fetchData()),
tap(() => console.log('Hide spinner'))
);

observable.subscribe(value => {
console.log(value); // Output: Data loaded
});

365/411
Explanation:

When the Observable is subscribed, it first emits 'Loading...' and shows the spinner.

After the switchMap operator switches to the fetchData() Observable (which simulates a delay),
the spinner is hidden once the data is loaded.

Conclusion
RxJS operators like of , from , interval , map , filter , mergeMap , switchMap , and others are
essential for creating and managing asynchronous streams in Angular applications. They allow you to
transform, filter, and combine data streams efficiently.

By using these operators, you can handle complex asynchronous workflows in a concise and readable
manner, avoiding callback hell and managing concurrency more effectively.

Making HTTP Calls With HttpClient


05:46
Making HTTP Calls With Observable
02:38
Implementing HTTP POST Request
05:20
Modifying Data With PUT Request
04:47
Removing Data With DELETE Request
03:41
Task - CRUD App - Displaying Products With GET Request (Part 1)
05:45
Task - CRUD App - Adding Products With POST Request (Part 2)
06:02
Task - CRUD App - Fetching Products Data Before Updating (Part 3)
06:37
Task - CRUD App - Updating Products With PUT Request (Part 4)
03:27
Task - CRUD App - Deleting Products With DELETE Request (Part 5)

HTTP Calls with HttpClient in Angular


In Angular, the HttpClient module is used for making HTTP requests. It allows you to communicate
with a backend server by sending HTTP requests and receiving responses. Below, I will explain some
common HTTP methods (GET, POST, PUT, DELETE) and show examples of how to implement them
using Angular's HttpClient .

366/411
1. Making HTTP Calls with HttpClient
To make HTTP requests, you need to import the HttpClientModule and inject HttpClient into your
component or service.

Example:

Step 1: Import the necessary modules in your app module ( app.module.ts ).

typescript

import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [HttpClientModule],
})
export class AppModule {}

Step 2: Inject HttpClient into a service or component to make HTTP requests.

typescript

import { HttpClient } from '@angular/common/http';


import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class ProductService {
private apiUrl = 'https://api.example.com/products'; // Sample API URL

constructor(private http: HttpClient) {}

getProducts(): Observable<any> {
return this.http.get(this.apiUrl); // GET request to fetch data
}
}

In the above code:

HttpClient is used to make HTTP requests.

The getProducts method performs an HTTP GET request to fetch data from the backend API.

367/411
2. Making HTTP Calls with Observable
The HttpClient methods return an Observable, which means you can subscribe to the HTTP call to
get the response.

Example:

typescript

this.productService.getProducts().subscribe((data) => {
console.log(data); // Handle the fetched data here
});

In this example:

We subscribe to the getProducts method, and once the data is returned, we handle it inside the
subscribe() method.

3. Implementing HTTP POST Request


A POST request is used to send data to the server to create a new resource.

Example:

typescript

addProduct(product: any): Observable<any> {


return this.http.post(this.apiUrl, product);
}

To use this method, you would typically call it from your component:

typescript

const newProduct = { name: 'Product 1', price: 100 };


this.productService.addProduct(newProduct).subscribe(response => {
console.log(response); // Handle the response from the POST request
});

In this example:

addProduct sends a POST request with a product object as the request body.

The server will process the request and return a response (usually the created object or a success
message).

368/411
4. Modifying Data with PUT Request
A PUT request is used to update an existing resource on the server.

Example:

typescript

updateProduct(id: number, updatedProduct: any): Observable<any> {


return this.http.put(`${this.apiUrl}/${id}`, updatedProduct);
}

To use this method:

typescript

const updatedProduct = { name: 'Updated Product', price: 150 };


this.productService.updateProduct(1, updatedProduct).subscribe(response => {
console.log(response); // Handle the response from the PUT request
});

In this example:

updateProduct sends a PUT request to update an existing product based on its id .

5. Removing Data with DELETE Request


A DELETE request is used to remove a resource from the server.

Example:

typescript

deleteProduct(id: number): Observable<any> {


return this.http.delete(`${this.apiUrl}/${id}`);
}

To use this method:

typescript

this.productService.deleteProduct(1).subscribe(response => {
console.log(response); // Handle the response from the DELETE request

369/411
});

In this example:

deleteProduct sends a DELETE request to remove a product from the backend server by its id .

6. Task - CRUD App - Displaying Products with GET Request (Part 1)


In this task, you’ll create a simple CRUD application to display a list of products.

Component Setup:

typescript

import { Component, OnInit } from '@angular/core';


import { ProductService } from './product.service';

@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
})
export class ProductListComponent implements OnInit {
products: any[] = [];

constructor(private productService: ProductService) {}

ngOnInit() {
this.productService.getProducts().subscribe((data) => {
this.products = data;
});
}
}

Here:

The ProductListComponent retrieves the list of products when the component initializes
( ngOnInit ).

It uses the getProducts method from the ProductService to make the HTTP GET request.

7. Task - CRUD App - Adding Products with POST Request (Part 2)

370/411
In this part of the task, you'll allow users to add products using the POST request.

Component Setup:

typescript

import { Component } from '@angular/core';


import { ProductService } from './product.service';

@Component({
selector: 'app-product-add',
templateUrl: './product-add.component.html',
})
export class ProductAddComponent {
newProduct = { name: '', price: 0 };

constructor(private productService: ProductService) {}

addProduct() {
this.productService.addProduct(this.newProduct).subscribe((response) => {
console.log('Product added:', response);
});
}
}

In this example:

The ProductAddComponent provides a form for adding a new product.

Upon form submission, the addProduct method sends a POST request to the backend to add the
new product.

8. Task - CRUD App - Fetching Products Data Before Updating (Part 3)


Before updating a product, you need to fetch its current data using the GET request.

Component Setup:

typescript

import { Component, OnInit } from '@angular/core';


import { ActivatedRoute } from '@angular/router';
import { ProductService } from './product.service';

@Component({
selector: 'app-product-edit',

371/411
templateUrl: './product-edit.component.html',
})
export class ProductEditComponent implements OnInit {
product: any = { name: '', price: 0 };

constructor(
private productService: ProductService,
private route: ActivatedRoute
) {}

ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
this.productService.getProductById(id).subscribe((data) => {
this.product = data;
});
}
}

Here:

ProductEditComponent fetches the existing product data before allowing the user to edit it.

It uses the getProductById method from the service to fetch the product data by its id .

9. Task - CRUD App - Updating Products with PUT Request (Part 4)


In this part, you will update an existing product using the PUT request.

Component Setup:

typescript

updateProduct() {
this.productService.updateProduct(this.product.id, this.product).subscribe((response) => {
console.log('Product updated:', response);
});
}

This method sends a PUT request to update the product on the server.

10. Task - CRUD App - Deleting Products with DELETE Request (Part 5)

372/411
Lastly, you'll implement the feature to delete a product using the DELETE request.

Component Setup:

typescript

deleteProduct(id: number) {
this.productService.deleteProduct(id).subscribe((response) => {
console.log('Product deleted:', response);
});
}

The deleteProduct method will send a DELETE request to the server to remove the product by its id .

Conclusion
GET: Retrieves data from the server.

POST: Sends new data to the server to create a resource.

PUT: Updates an existing resource on the server.

DELETE: Removes a resource from the server.

By implementing these methods using Angular’s HttpClient , you can build robust CRUD applications
that interact with backend services seamlessly.

Introduction to Signals
01:59
Creating Signal
03:44
IQ - Creating Signal
01:05
Updating Signal Value
03:10
IQ - update() method
01:30
Task - To-do List
07:45
Computed Signals
04:13
IQ - Computed Signals
01:35
Understanding effect() function
04:55

373/411
Cleaning up the effect()
05:15
Untracking Signals
05:07
Task - Updating The Cart using Signals
07:31
Linked Signals
04:53
Converting Observable To Signal
03:53
Task - Filtering Products Based on User Input with linkedSignal()

Introduction to Signals in Angular


In Angular, Signals are a feature introduced to manage state and handle reactive programming. They
are particularly useful when working with reactive UI components. Signals allow you to create reactive
data sources and automatically update the DOM or other components when their values change. This
is very useful when you need to track and react to changes in the state.

Let’s dive into the concepts related to Signals, including their creation, updates, and common use cases
such as tasks or to-do lists.

1. Creating a Signal
A Signal can be created to store reactive values, similar to variables in traditional programming but
with the ability to trigger updates when changed.

Example:

typescript

import { signal } from '@angular/core';

const counterSignal = signal(0); // Creates a signal with initial value 0

In this example, counterSignal is a signal that starts with a value of 0 .

2. Updating Signal Value


To update the value of a signal, you can use the update() method. This method allows you to modify
the value of a signal reactively.

374/411
Example:

typescript

counterSignal.update((value) => value + 1); // Increments the signal's value

In this example:

update() is used to modify the signal value. The provided function receives the current value of
the signal and updates it.

3. Task - To-do List using Signals


You can use signals to create a to-do list application where the state of the list is reactive. Each time you
add or remove a task, the signal will automatically update the UI.

Example:

typescript

import { signal } from '@angular/core';

const todoListSignal = signal<string[]>([]); // Creates a signal to store a list of to-dos

function addTodo(newTodo: string) {


todoListSignal.update((todos) => [...todos, newTodo]); // Adds a new todo to the list
}

function removeTodo(index: number) {


todoListSignal.update((todos) => todos.filter((_, i) => i !== index)); // Removes a todo by
index
}

Here:

todoListSignal holds the list of tasks.

addTodo() and removeTodo() methods update the signal when a task is added or removed.

4. Computed Signals
Computed Signals are signals that derive their value from other signals. They automatically update
when the signals they depend on change.

375/411
Example:

typescript

import { computed } from '@angular/core';

const countSignal = signal(0);


const computedSignal = computed(() => countSignal() * 2); // Automatically updates when
countSignal changes

In this example:

computedSignal is dependent on countSignal and will always be double the value of


countSignal .

5. Understanding effect() function


The effect() function is used to perform side effects based on signal changes. When a signal's value
changes, the effect is triggered, making it useful for actions such as logging or DOM updates.

Example:

typescript

import { effect } from '@angular/core';

const countSignal = signal(0);

effect(() => {
console.log('Signal value changed:', countSignal());
});

Here:

The effect() function logs the value of countSignal whenever it changes.

6. Cleaning up the effect()


You can clean up or unsubscribe from effects to prevent unnecessary re-renders or memory leaks
when components are destroyed or when the effect is no longer needed.

Example:

376/411
typescript

import { effect } from '@angular/core';

const countSignal = signal(0);

const cleanup = effect(() => {


console.log('Signal value changed:', countSignal());
});

// Cleanup the effect after some time or condition


setTimeout(() => cleanup(), 5000); // Stops the effect after 5 seconds

Here:

The cleanup function is called to stop the effect after a specific period or condition.

7. Untracking Signals
Untracking a signal means that you stop tracking its changes. This is useful when you no longer need
to react to changes in the signal.

Example:

typescript

import { untrack } from '@angular/core';

const countSignal = signal(0);

untrack(() => {
console.log('This will not react to countSignal changes');
});

In this example:

untrack() prevents the code inside from reacting to changes in the signal value.

8. Task - Updating the Cart using Signals


In an e-commerce app, you can manage the shopping cart state reactively using signals.

Example:

377/411
typescript

const cartSignal = signal<{ id: string, quantity: number }[]>([]);

function addToCart(item: { id: string, quantity: number }) {


cartSignal.update((cart) => [...cart, item]);
}

function updateQuantity(itemId: string, quantity: number) {


cartSignal.update((cart) => cart.map(item => item.id === itemId ? { ...item, quantity } :
item));
}

Here:

cartSignal holds the list of cart items.

addToCart() adds a new item to the cart.

updateQuantity() updates the quantity of an existing item in the cart.

9. Linked Signals
Linked signals are signals that depend on each other. When one signal changes, it automatically
updates another signal.

Example:

typescript

import { linkedSignal } from '@angular/core';

const priceSignal = signal(100);


const discountSignal = signal(10);

const finalPriceSignal = linkedSignal(priceSignal, discountSignal, (price, discount) => price


- discount);

In this example:

finalPriceSignal automatically updates whenever either priceSignal or discountSignal


changes.

378/411
10. Converting Observable to Signal
Sometimes, you may want to convert an Observable to a Signal to work with reactive states in Angular.

Example:

typescript

import { from } from 'rxjs';


import { toSignal } from '@angular/core';

const observable$ = from([1, 2, 3]);

const signalFromObservable = toSignal(observable$);

In this example:

toSignal() converts an Observable ( observable$ ) into a Signal ( signalFromObservable ).

11. Task - Filtering Products Based on User Input with linkedSignal()


To filter products based on user input, you can use linkedSignal() to reactively update the filtered
list whenever the input or product list changes.

Example:

typescript

const productsSignal = signal([


{ id: 1, name: 'Product 1' },
{ id: 2, name: 'Product 2' },
]);

const searchTermSignal = signal('');

const filteredProductsSignal = linkedSignal(


productsSignal,
searchTermSignal,
(products, searchTerm) => products.filter(product => product.name.includes(searchTerm))
);

Here:

filteredProductsSignal dynamically updates whenever either productsSignal or

searchTermSignal changes.

379/411
Conclusion
Signals in Angular are powerful tools for managing state reactively. They help in building highly
responsive applications by automatically updating components when the underlying state changes.
From simple use cases like managing to-do lists or shopping carts, to more complex scenarios like
filtering and linked signals, Signals provide a clean and efficient way to handle state in modern Angular
applications.

Introduction - CSR, SSR & SSG


02:23
Understanding The Initial Deployment Phase
04:28
Discussing the CSR and SPA’s
03:48
SPA Deployment
05:10
From Client To Server-Side - SSR Migration
05:36
Serving the SSR App
02:35
Optimizing Code for Server-Side Rendering (SSR)
04:14
Understanding Static Site Generation(SSG)
02:17
Implementing SSG
05:01
Understanding Hybrid Rendering

Introduction - CSR, SSR & SSG


In modern web development, the rendering strategies of web pages significantly affect performance,
user experience, and SEO. The three main rendering strategies are:

1. CSR (Client-Side Rendering): In CSR, the browser loads a minimal HTML page, and JavaScript is
responsible for rendering the content dynamically. This is common in Single Page Applications
(SPA), where the page doesn't reload, and content updates based on user interaction. The first
page load might take longer, but subsequent page transitions are fast because only necessary data
is fetched and updated.

2. SSR (Server-Side Rendering): SSR is where the server generates the full HTML for a page on each
request, which is then sent to the client. This allows the browser to render the page immediately,

380/411
making it SEO-friendly and faster for the first render. After the initial load, it can switch to a more
interactive SPA-like behavior.

3. SSG (Static Site Generation): SSG is a method of pre-rendering the HTML at build time. This means
HTML files are generated for each page and stored on the server before the user requests them.
It’s great for websites with static content that doesn't change often, ensuring fast load times and
better SEO.

Understanding The Initial Deployment Phase


The initial deployment phase involves preparing the application to be hosted on a server or cloud
infrastructure. It includes:

Setting up environment variables: Define configurations, API URLs, and other settings needed for
production.

Minifying the code: Compress the JavaScript, CSS, and other assets to reduce load times.

Bundling the assets: Group all JavaScript and CSS into smaller files to make delivery faster.

Setting up the server: Ensure that the correct software is running on the server (e.g., web server,
Node.js server for SSR, etc.).

Discussing the CSR and SPA’s


CSR (Client-Side Rendering) is tightly associated with SPA (Single Page Application), where a
single HTML page is loaded, and subsequent content is dynamically rendered using JavaScript
frameworks like Angular, React, or Vue.js.

The advantage of SPA is faster subsequent page loads, as the app doesn't need to reload the entire
page. However, the initial load might take a bit longer due to the JavaScript files and other
resources that need to be fetched.

SPA Deployment
For SPA deployment, the entire application is bundled and deployed as static files (HTML, CSS, JS)
on a server or CDN.

381/411
In production, a server (e.g., Node.js) might serve the SPA or directly serve static files with minimal
backend logic.

Steps for SPA deployment:

1. Build the project: Use the Angular CLI or other tools to bundle your app.

2. Deploy the static assets: Host the files on a web server or CDN.

3. Routing configuration: Ensure that the routing is handled properly using pathLocationStrategy
to avoid 404 errors for direct URLs.

From Client To Server-Side - SSR Migration


Migrating from a CSR app to an SSR (Server-Side Rendering) app typically involves:

1. Configuring server-side rendering: Using frameworks like Angular Universal (for Angular apps),
which allows rendering pages on the server before sending them to the browser.

2. Handling dynamic content: Content that changes based on user input must be rendered on the
server, and the data must be fetched server-side before the page is sent to the browser.

3. SEO considerations: Since SSR pre-renders pages, it allows search engines to index the content
better, providing a significant SEO benefit.

Steps for SSR migration:

1. Set up Angular Universal or other SSR frameworks.

2. Modify the app to use server-side rendering strategies for routing and content.

3. Ensure the API calls are correctly handled server-side before the page is rendered.

Serving the SSR App


For SSR, the app is typically served using a Node.js server with Angular Universal. This server-side
application generates the HTML on the server and serves it to the browser.

Steps to serve SSR app:

1. Set up the server-side rendering with a Node.js server.

2. Install required dependencies for SSR like @angular/platform-server and @angular/universal .

3. Create server files (e.g., server.ts or app.server.module.ts ) to handle the SSR logic.

382/411
Optimizing Code for Server-Side Rendering (SSR)
To optimize your app for SSR:

1. Lazy Loading: Implement lazy loading of modules to reduce the amount of JavaScript that needs
to be initially loaded.

2. Avoid window/document references: Since the server doesn’t have access to the browser’s
window or document , any code that relies on them should be handled differently or only run on
the client.

3. Pre-fetching Data: Pre-fetch or pre-load critical data on the server to ensure that the page loads
faster.

Understanding Static Site Generation (SSG)


Static Site Generation is the process of generating static HTML files at build time. These files are served
directly to the client, without the need for dynamic server-side generation.

Advantages of SSG:

Speed: Since the HTML is pre-rendered, the pages load incredibly fast.

SEO: Search engines can easily crawl static pages, improving SEO.

Cost: Since the pages are static, they can be hosted on simple file servers or CDNs at a low cost.

Implementing SSG
To implement SSG, you would:

1. Generate static pages for each URL of your site at build time (using tools like Next.js, Gatsby, or
Angular Static Generator).

2. Serve static assets through a CDN to ensure faster delivery and better global reach.

3. Ensure that any content that needs to be dynamically updated (e.g., user comments, login state) is
handled via client-side JavaScript.

383/411
Understanding Hybrid Rendering
Hybrid Rendering combines CSR, SSR, and SSG to use the right approach based on the needs of
specific pages in your app. For instance, you might use SSR for critical SEO pages, SSG for static
content, and CSR for highly interactive features.

Example:

SSR might be used for the homepage, product pages, and blog posts (for SEO benefits).

SSG could be used for a documentation site, where the content is rarely updated.

CSR would be used for user-specific pages like the dashboard, where content is highly interactive
and frequently changing.

Conclusion
Each rendering method—CSR, SSR, and SSG—has its own advantages, and choosing the right one
depends on your specific needs, such as performance, SEO, and user experience. Migrating from CSR
to SSR or implementing SSG requires understanding your app's requirements and optimizing code
accordingly. Hybrid rendering provides a flexible approach, allowing you to leverage the best of each
rendering strategy.

Let's break down each concept in detail with examples to help you understand them better.

Introduction - CSR, SSR & SSG


Before diving into examples, let’s define these three rendering strategies:

1. CSR (Client-Side Rendering): The entire page (HTML, CSS, JS) is loaded initially, and then JavaScript
is used to render or update the content dynamically. This is common for Single Page Applications
(SPA) where the browser loads a minimal HTML page and dynamically updates the content as the
user interacts with the app.

2. SSR (Server-Side Rendering): The server generates the HTML content of the page and sends it to
the browser. This makes the page ready to be displayed immediately, which improves the SEO
(since the content is available on the server-side) and is beneficial for the first-time page load
performance.

3. SSG (Static Site Generation): Pages are pre-built at build time, and the generated HTML is served
to the client. It’s great for websites where content doesn’t change often (e.g., blogs or
documentation). It allows fast loading times and excellent SEO.

384/411
CSR Example
Let’s start with a simple Angular component that shows a list of users, which can be fetched using
Client-Side Rendering.

CSR (Angular SPA)

ts

// user-list.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-user-list',
template: `
<h2>User List</h2>
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
`
})
export class UserListComponent implements OnInit {
users: any[] = [];

constructor(private http: HttpClient) {}

ngOnInit() {
// Fetch data from API on client-side
this.http.get('https://jsonplaceholder.typicode.com/users')
.subscribe((data: any[]) => {
this.users = data;
});
}
}

Explanation: The list of users is fetched on the client-side when the component is initialized
( ngOnInit ). The page will display a loading spinner initially until the data is loaded.

Note: CSR has a slight delay in the first page load, but once loaded, it’s faster as only data is
fetched in subsequent requests.

SSR Example (Server-Side Rendering with Angular Universal)

385/411
In Angular Universal (SSR), the initial rendering of the page happens on the server. The page is served
to the browser with pre-rendered HTML, improving the first-page load performance and SEO.

SSR with Angular Universal

1. Setting up Angular Universal: Run the following command to add Angular Universal to your
existing Angular project:

bash

ng add @nguniversal/express-engine

This will configure your app to render on the server.

2. Modify the app.server.module.ts :

ts

import { NgModule } from '@angular/core';


import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
imports: [AppModule, ServerModule],
bootstrap: [AppComponent]
})
export class AppServerModule {}

3. Serving SSR app:

Now, after building the app ( ng build --prod && ng run your-project-name:server ), your Angular
app will be rendered on the server. When you visit a page, the server will send pre-rendered HTML to
the browser.

Explanation: The server sends fully-rendered HTML to the browser, improving SEO and initial page
load performance. After the initial load, the app behaves like a typical Angular SPA.

SSG Example (Static Site Generation with Next.js)


SSG is typically used for static sites where the content does not change often (e.g., blogs,
documentation). Next.js is a popular framework for React that supports Static Site Generation.

SSG with Next.js

386/411
1. Set up a page that will use SSG:

Create a pages/index.js file:

js

// pages/index.js
import React from 'react';

export async function getStaticProps() {


// Simulating fetching data during build time
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await res.json();

return {
props: {
users
}
};
}

const Home = ({ users }) => {


return (
<div>
<h1>User List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};

export default Home;

Explanation: The getStaticProps function runs at build time and fetches the list of users. These
users are then passed to the component as props, and the static HTML is generated during the
build process.

Note: This is Static Site Generation (SSG), where the HTML is generated once at build time. The
pages are fast because they are served as static files.

387/411
Hybrid Rendering Example
Hybrid Rendering is a combination of CSR, SSR, and SSG. For example, a website could use SSR for the
homepage (to get fast first load and SEO benefits), SSG for the blog (since the blog doesn't change
frequently), and CSR for the dashboard (since it's highly interactive and personalized).

Example of Hybrid Rendering Strategy

In an Angular Universal app, you could use SSR for SEO-friendly pages and CSR for user-specific
content (like a dashboard).

SSR: Used for homepage, product pages, etc.

SSG: Used for static content like blogs or documentation.

CSR: Used for personalized, dynamic content (e.g., a user dashboard or admin panel).

Preloading and Lazy Loading Example


Preloading and Lazy Loading are strategies used to optimize the loading of JavaScript bundles in an
Angular app.

1. Lazy Loading: Load modules only when required (e.g., when navigating to a specific route).

ts

// In app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', loadChildren: () => import('./products/products.module').then(m =>
m.ProductsModule) }
];

Explanation: The ProductsModule is lazy-loaded when the user navigates to /products .

2. Preloading: You can preload modules after the initial app load to improve navigation speed.

ts

// In app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', loadChildren: () => import('./products/products.module').then(m =>
m.ProductsModule) }
];

388/411
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})
export class AppRoutingModule {}

Explanation: The PreloadAllModules strategy will preload all lazy-loaded modules in the
background after the app is initially loaded.

Summary of Key Points:


CSR (Client-Side Rendering) is great for dynamic, highly interactive applications but may have a
slower first-page load.

SSR (Server-Side Rendering) provides better SEO and faster initial load times, but it can be more
complex to set up.

SSG (Static Site Generation) generates static HTML at build time, making it ideal for content that
doesn’t change often.

Hybrid Rendering uses a combination of CSR, SSR, and SSG to maximize performance and SEO.

Lazy Loading helps you load only the parts of the app that are needed, improving the
performance of large applications.

Preloading optimizes lazy-loaded routes by loading them in the background.

Introduction to Change Detection


06:05
Expression Errors while Detecting Changes
02:44
Optimizing Code for Change Detection
05:41
IQ - Optimizing Code for Change Detection
01:28
Change Detection with OnPush Strategy
05:25
Change Detection with Inputs
04:06
OnPush + Signals: Understanding Component Data Sharing
04:40
OnPush + Signals: Problem with Cross-Component Data Sharing
02:37

389/411
Manual Change Detection - RxJS Subjects
05:44
Using Async Pipe with BehaviorSubject
02:27
Implementing Zoneless Change Detection
explain in detail with examples

Introduction to Change Detection in Angular


Change detection in Angular is the mechanism through which Angular keeps track of the state of your
application and updates the DOM when data changes. Angular uses change detection to ensure that
the view is in sync with the underlying model.

Angular checks for changes in the model (component data) and updates the view accordingly. When
something changes in the application (e.g., user interaction, API call), Angular checks whether the view
needs to be updated to reflect the new state of the model.

Expression Errors while Detecting Changes


Expression errors are common when Angular tries to detect changes in expressions and encounters
issues in your component's data. These can occur when:

1. A model property or method is not properly initialized.

2. There’s a problem in accessing a property in an asynchronous operation before it has a value.

For example:

ts

// Incorrect use of an object property when it's undefined


@Component({
selector: 'app-user',
template: `{{ user.name }}`
})
export class UserComponent {
user: any; // uninitialized user
}

In this case, Angular will throw an expression error because the user object is undefined when
Angular tries to read user.name .

Solution: To avoid expression errors, you can use safe navigation ( ?. ) to ensure that the object exists
before accessing its properties:

html

390/411
<!-- Safely access user.name -->
<p>{{ user?.name }}</p>

Optimizing Code for Change Detection


Angular performs change detection in a "dirty checking" manner. This means Angular checks every
bound property and updates the DOM if the property has changed. This process can be expensive in
large applications with many bindings, leading to performance issues.

Optimization strategies include:

1. OnPush Change Detection Strategy: This strategy tells Angular to check for changes only when
specific conditions are met, reducing the number of checks performed.

2. Manual Change Detection: This allows you to manually trigger change detection only when
necessary.

3. Use of trackBy in ngFor: When rendering lists, using trackBy helps Angular optimize rendering
by only updating the items that have changed.

Change Detection with OnPush Strategy


The OnPush change detection strategy optimizes the detection mechanism by checking for changes
only when certain conditions are met. By default, Angular checks for changes in all components, even if
their data hasn't changed. With OnPush, Angular only checks a component if:

The component’s inputs change (e.g., a new value is passed into the component).

An event (like a click or input event) occurs within the component.

An observable or promise emits new data.

Example:

ts

@Component({
selector: 'app-user',
template: `{{ user.name }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {

391/411
@Input() user: { name: string };
}

With OnPush change detection, Angular will only recheck the UserComponent if the user input
changes (or if any other conditions like events occur).

Change Detection with Inputs


When you use the @Input() decorator to pass data to a component, Angular automatically triggers
change detection for that component. However, if you're using OnPush, Angular will only check the
component for changes if the input property changes.

ts

@Component({
selector: 'app-child',
template: `{{ data }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
@Input() data: string;
}

@Component({
selector: 'app-parent',
template: `<app-child [data]="parentData"></app-child>`
})
export class ParentComponent {
parentData = 'Initial Data';
updateData() {
this.parentData = 'Updated Data'; // This triggers change detection for ChildComponent
}
}

In this example:

The ChildComponent will only detect changes when the parentData changes.

OnPush + Signals: Understanding Component Data Sharing

392/411
With OnPush and Signals (as discussed in a previous part about signals in Angular), components can
share data in an efficient way. When using signals, you can ensure that changes are detected only
when necessary by associating signals with a component's input properties.

Here’s an example of how OnPush works in conjunction with signals:

ts

@Component({
selector: 'app-user',
template: `{{ signal.value }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
signal = signal('Hello World');
}

In this case, signal.value will be tracked for changes. If signal.value changes, the component will
be updated, as OnPush only triggers change detection when a relevant change occurs.

OnPush + Signals: Problem with Cross-Component Data Sharing


One challenge with OnPush and Signals is cross-component data sharing. If one component's signal
is updated but the change is not reflected in other components (because of OnPush), you may
experience stale or inconsistent data across components.

To solve this problem, you may need to manually trigger change detection in the parent component or
use Angular services to propagate changes across components.

Manual Change Detection - RxJS Subjects


You can also use RxJS Subjects to manually trigger change detection in components that use OnPush.

For example, using a BehaviorSubject:

ts

@Component({
selector: 'app-parent',
template: `<app-child [data]="data$ | async"></app-child>`
})
export class ParentComponent {

393/411
private dataSubject = new BehaviorSubject<string>('Initial Value');
data$ = this.dataSubject.asObservable();

changeData() {
this.dataSubject.next('Updated Value');
}
}

@Component({
selector: 'app-child',
template: `{{ data }}`
})
export class ChildComponent {
@Input() data: string;
}

In this case:

The ParentComponent uses an RxJS BehaviorSubject to manage the data.

The ChildComponent subscribes to the observable ( data$ ) to receive updates.

When the parent component calls changeData() , the BehaviorSubject emits a new value, and
the child component receives the updated data.

Using Async Pipe with BehaviorSubject


The Async Pipe allows Angular to automatically subscribe to observables and manage subscriptions. It
works seamlessly with RxJS subjects such as BehaviorSubject , ReplaySubject , etc.

ts

@Component({
selector: 'app-parent',
template: `<app-child [data]="data$ | async"></app-child>`
})
export class ParentComponent {
private dataSubject = new BehaviorSubject<string>('Initial Value');
data$ = this.dataSubject.asObservable();

changeData() {
this.dataSubject.next('Updated Value');
}
}

394/411
In the above example:

The Async Pipe automatically subscribes to the observable ( data$ ).

Whenever the BehaviorSubject emits a new value, Angular updates the view with the latest value.

Implementing Zoneless Change Detection


Zoneless Change Detection refers to the concept of managing change detection without using
Angular's NgZone (which normally triggers change detection when events are fired).

In a Zoneless application, you manage the change detection process manually, without relying on
Angular's zone. You can use RxJS or ChangeDetectorRef to handle manual triggering of change
detection.

ts

@Component({
selector: 'app-example',
template: `<p>{{ value }}</p>`
})
export class ExampleComponent {
value = 'Hello World';

constructor(private cdRef: ChangeDetectorRef) {}

triggerChangeDetection() {
this.value = 'Updated Value';
this.cdRef.detectChanges(); // Manually trigger change detection
}
}

In this example, after changing the value , we manually trigger change detection using
cdRef.detectChanges() . This is useful when you don't want to rely on Angular's zones for
performance reasons.

Summary of Concepts:
1. Change Detection is how Angular keeps track of the state of the application and updates the DOM
accordingly.

395/411
2. Expression errors happen when Angular tries to evaluate an expression that’s either undefined or
doesn’t exist.

3. OnPush change detection strategy optimizes performance by checking only when inputs change,
events are triggered, or observables emit.

4. Manual Change Detection with RxJS allows you to explicitly control when Angular should update
the view.

5. Async Pipe is a convenient way to subscribe to observables and automatically manage


subscriptions.

6. Zoneless Change Detection is a performance optimization technique where you manually trigger
change detection without Angular's NgZone.

These techniques can be combined depending on the complexity of the application and the
performance optimizations you need.

Q4. What are some important string operations in JS?


02:10
Q5. What is DOM? What is the difference between HTML and
DOM?
02:31
Q6. What are selectors in JS?
01:05
Q7. Difference getElementById, getElementsByClassName and get
elementsByTagName?
02:42
Q8. What are data types in JS?
01:23
Q9. What are operators? What are the types of operators in JS?
03:46
Q10. What are the types of conditions statements in JS?
03:19
Q11. What is a loop? What are the types of loops in JS?
01:25
Q12. What are Functions in JS? What are the types of function?
01:26
Q13. What are Arrow Functions in JS? What is it use?
02:14
Q14. What are Arrays in JS? How to get, add & remove elements
from arrays?
02:59
Q15. What are Objects in JS?
02:00
Q16. What is Scope in JavaScript?
01:24

396/411
Q17. What is Hoisting in JavaScript?
01:49
Q18. What is Error Handling in JS?
01:16
Q19. What is JSON?
01:00
Q20. What is asynchronous programming in JS? What is its use?
03:27
Variables & Datatypes - Introduction
00:40
Q21. What are variables? What is the difference between var, let,
and const ?
03:32
Q22. What are data types in JS?
01:23
Q23. What is the difference between primitive and non-primitive
data types?
04:07
Q24. What is the difference between null and undefined in JS?
02:22
Q25. What is the use of typeof operator?
01:16
Q26. What is type coercion in JS?
01:41
Operators & Conditions - Introduction
00:34
Q27. What are operators? What are the types of operators in JS?
03:46
Q28. What is the difference between unary, binary, and ternary
operators?
01:33
Q29. What is short-circuit evaluation in JS?
02:16
Q30. What is operator precedence?
00:54
Q31. What are the types of conditions statements in JS?
03:19
Q32. When to use which type of conditions statements in real
applications?
03:32
Q33. What is the difference between == and ===?
01:46
Q34. What is the difference between Spread and Rest operator in
JS?
03:26
Arrays - Introduction

397/411
00:46
Q35. What are Arrays in JS? How to get, add & remove elements
from arrays?
02:59
Q36. What is the indexOf() method of an Array?
00:48
Q37. What is the difference between find() and filter() methods of
an Array?
03:02
Q38. What is the slice() method of an Array?
01:16
Q39. What is the difference between push() and concat () methods
of an Array ?
01:27
Q40. What is the difference between pop() and shift() methods of
an Array?
01:22
Q41. What is the splice() method of an Array?
03:27
Q42. Difference between the slice() and splice() methods of an
Array?
00:40
Q43. What is the difference map() and for Each() array methods of
an Array?
02:37
Q44. How to sort and reverse an array?
00:51
Q45. What is Array Destructuring in JS?
01:38
Q46. What are array-like objects In JS?
02:52
Q47. How to convert an array-like object into an array?
01:33
Loops - Introduction
00:35
Q48. What is a loop? What are the types of loops in JS?
01:25
Q49. What is the difference between while and for loops?
02:13
Q50. What is the difference between while and do-while loops?
01:50
Q51. What is the difference between break and continue
statement?
01:35
Q52. What is the difference between for and for…of loop in JS?
01:32

398/411
Q53. What is the difference between for…of and for…in loop?
01:28
Q54. What is forEach method? Compare it with for…of and for…in
loop?
02:32
Q55. When to use for…of loop and when to use forEach method in
applications?
01:39
Functions - Introduction
00:37
Q56. What are Functions in JS? What are the types of function?
01:26
Q57. Difference between named and anonymous functions?
01:48
Q58. What is function expression in JS?
01:11
Q59. What are Arrow Functions in JS? What is it use?
02:14
Q60. What are Callback Functions? What is it use?
02:26
Q61. What is Higher-order function In JS?
02:14
Q62. What is the difference between arguments and parameters?
00:44
Q63. In how many ways can you pass arguments to a function?
01:42
Q64. How do you use default parameters in a function?
00:56
Q65. What is the use of event handling in JS?
02:40
Q66. What are First-Class functions in JS?
01:25
Q67. What are Pure and Impure functions in JS?
02:57
Q68. What is Function Currying in JS?
02:34
Q69. What are call, apply and bind methods in JS?
02:34
Strings - Introduction
00:25
Q70. What is a String?
00:19
Q71. What are template literals and string interpolation in strings?
01:31
Q72. Difference between single quotes (''), double quotes ("") &
backticks('') ?

399/411
00:37
Q73. What are some important string operations in JS?
02:10
Q74. What is string immutability?
01:34
Q75. In how many ways you can concatenate strings?
01:17
DOM - Introduction
00:30
Q76. What is DOM? What is the difference between HTML and
DOM?
02:31
Q77. How do you select, modify, create and remove DOM
elements?
00:56
Q78. What are selectors in JS?
01:05
Q79. Difference between
getElementById,getElementsByClassName& getElementsByTag?
02:42
Q80. What is the difference between querySelector() and
querySelectorAll()?
01:07
Q81. What are the methods to modify elements properties and
attributes?
00:39
Q82. What is the difference between innerHTML and textContent?
01:24
Q83. How to add and remove properties of HTML elements in the
DOM using JS?
01:07
Q84. How to add and remove style from HTML elements in DOM
using JS?
00:56
Q85. Create new elements in DOM using JS?
02:20
Q86. What is the difference between createElement() and
createTextNode()?
01:05
Error Handling- Introduction
00:27
Q87. What is Error Handling in JS?
01:16
Q88. What is the role of finally block in JS?
01:21
Q89. What is the purpose of the throw statement in JS?

400/411
01:30
Q90. What is Error propagation in JS?
00:38
Q91. What are the best practices for error handling?
01:02
Q92. What are the different types of errors In JS?
01:18
Objects - Introduction
00:33
Q93. What are Objects in JS?
02:00
Q94. In how many ways we can create an object?
01:36
Q95. What is the difference between an array and an object?
00:57
Q96. How do you add or modify or delete properties of an object?
00:37
Q97. Explain the difference between dot notation and bracket
notation?
01:24
Q98. What are some common methods to iterate over the
properties of an object?
01:32
Q99. How do you check if a property exists in an object?
01:23
Q100. How do you clone or copy an object?
01:48
Q101. What is the difference between deep copy and shallow copy
in JS?
02:46
Q102. What is Set Object in JS?
02:27
Q103. What is Map Object in JS?
01:26
Q104. What is the difference between Map and Object in JS?
01:01
Events - Introduction
00:32
Q105. What are Events? How are events triggered?
01:40
Q106. What are the types of events in JS?
01:05
Q107. What is Event Object in JS?
02:02
Q108. What is Event Delegation in JS?
02:01

401/411
Q109. What is Event Bubbling In JS?
01:40
Q110. How can you stop event propagation or event bubbling in
JS?
01:10
Q111. What is Event Capturing in JS?
01:42
Q112. What is the purpose of the event.preventDefault() method in
JS?
01:08
Q113. What is the use of "this" keyword in the context of event
handling in JS?
00:38
Q114. How to remove an event handler from an element in JS?
00:59
Closures - Introduction
00:30
Q115. Explain the concept of Lexical Scoping?
01:16
Q116. What is Closure?
01:53
Q117. What are the benefits of Closures?
04:34
Q118. What is the concept of Encapsulation in the context of
closures?
01:21
Q119. What are the disadvantage or limitations of Closures?
01:02
Q120. How can you release the variable references or closures
from memory?
00:26
Q121. What is the difference between a Regular Function and a
Closure?
00:59
Asynchronous programming – Basics - Introduction
00:35
Q122. What is asynchronous programming in JS? What is its use?
03:27
Q123. What is the difference between synchronous and
asynchronous programming?
01:39
Q124. What are the techniques for achieving asynchronous
operations in JS?
00:37
Q125. What is setTimeout()? How is it used to handle
asynchronous operations?

402/411
02:09
Q126. What is setInterval()? How is it used to handle asynchronous
operations?
01:33
Q127. What is the role of callbacks in fetching API data
asynchronously?
02:27
Q128. What is callback hell? How can it be avoided?
01:44
Asynchronous Programming - Promises - Introduction
00:35
Q129. What are Promises in JavaScript?
02:45
Q130. How to implement Promises in JavaScript?
02:30
Q131. When to use Promises in real applications?
00:47
Q132. What is the use of Promise.all() method?
02:11
Q133. What is the use of Promise.race() method?
01:23
Q134. What is the difference between Promise.all() and
Promise.race()?
01:08
Asynchronous Programming – Async Await - Introduction
00:22
Q135. What is the purpose of async/ await? Compare it with
Promises?
04:15
Q136. Explain the use of async and await keywords in JS?
03:04
Q137. Can we use async keyword without await keyword and vice
versa?
00:44
Q138. How do you handle errors in async/ await functions?
00:30
Browser APIs & Web Storage - Introduction
00:25
Q139. What is a window object?
01:01
Q140. What are Browser APIs in JS?
01:52
Q141. What is Web Storage, and its use? How many types of web
storage are there?
02:05
Q142. What is Local Storage? How to store, retrieve and remove

403/411
data from it?
02:21
Q143. What is Session Storage? How to store, retrieve and remove
data from it?
01:49
Q144. What is the difference between LocalStorage and
SessionStorage?
02:36
Q145. How much data can be stored in localStorage and
sessionStorage?
00:34
Q146. What are cookies? How do you create and read cookies?
01:49
Q147. What is the difference between cookies and web storage?
01:23
Q148. When to use cookies and when to use web storage?
01:22
Classes, Constructors, this & Inheritance - Introduction
00:15
Q149. What are Classes in JS?
03:08
Q150. What is a constructor?
00:50
Q151. What are constructor functions?
00:50
Q152. What is the use of this keyword?
01:33
Q153. Explain the concept of prototypal inheritance?
02:20
ECMAScript & Modules - Introduction
00:26
Q154. What is ES6? What are some new features introduced by it?
01:05
Q155. What are Modules in JS?
02:36
Q156. What is the role of export keyword?
00:51
Q157. What are the advantages of modules?
00:56
Q158. What is the difference between named exports and default
exports?
01:01
Q159. What is the difference between static and dynamic imports?
01:22
Q160. What are module bundlers?
01:23

404/411
Security & Performance - Introduction
00:23
Q161. What is eval() function in JS?
00:49
Q162. What is XSS (Cross-Site Scripting) attack?
01:01
Q163. What is SQL Injection attack?
00:52
Q164. What are some best practices for security in JS?
01:19
Q165. What are the best practices for improving performance in
JS?

Here’s a detailed explanation of key topics in JavaScript based on your provided list:

Q4. Important String Operations in JS


1. concat() - Combines two or more strings into one.

js

let str1 = "Hello";


let str2 = "World";
console.log(str1.concat(" ", str2)); // "Hello World"

2. slice() - Extracts a section of a string.

js

let str = "Hello World";


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

3. replace() - Replaces part of a string with another string.

js

let str = "Hello World";


console.log(str.replace("World", "Universe")); // "Hello Universe"

4. toUpperCase() - Converts string to uppercase.

js

let str = "hello";

405/411
console.log(str.toUpperCase()); // "HELLO"

5. toLowerCase() - Converts string to lowercase.

js

let str = "HELLO";


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

6. charAt() - Returns the character at a specified index.

js

let str = "Hello";


console.log(str.charAt(1)); // "e"

7. trim() - Removes whitespace from both ends of a string.

js

let str = " Hello ";


console.log(str.trim()); // "Hello"

Q5. What is DOM? Difference between HTML and DOM?


DOM (Document Object Model) is a programming interface for web documents. It represents the
page so that programs can manipulate the structure, style, and content.

HTML is a static markup language that defines the structure of web pages, while DOM is a
dynamic, object-oriented representation of the HTML elements, allowing programs to access and
manipulate content.

Q6. What are Selectors in JS?


Selectors in JavaScript are used to select HTML elements so that we can interact with them. Common
methods include:

getElementById() : Selects an element by ID.

getElementsByClassName() : Selects elements by class.

querySelector() : Selects the first matching element based on CSS selectors.

406/411
querySelectorAll() : Selects all matching elements.

Q7. Difference between getElementById , getElementsByClassName , and


getElementsByTagName ?

getElementById(id) : Selects a single element by its ID.

getElementsByClassName(className) : Returns a live HTMLCollection of elements with the


specified class.

getElementsByTagName(tagName) : Returns a live HTMLCollection of elements with the specified tag


name.

Q8. What are Data Types in JS?


JavaScript has 7 primitive data types:

Number

String

Boolean

Object

Null

Undefined

Symbol (ES6)

Q9. What are Operators? Types of Operators in JS?


Operators are symbols used to perform operations on variables and values. Types of operators include:

1. Arithmetic Operators ( + , - , * , / , % )

2. Assignment Operators ( = , += , -= )

3. Comparison Operators ( == , === , > , < )

4. Logical Operators ( && , || , ! )

5. Bitwise Operators ( & , | , ^ , << , >> )

407/411
6. Ternary Operator ( condition ? expr1 : expr2 )

Q10. What are the Types of Condition Statements in JS?


if : Executes a block of code if the condition is true.

else : Executes an alternative block if the condition is false.

else if : Tests multiple conditions.

switch : Evaluates an expression and matches it with several cases.

Q11. What is a Loop? Types of Loops in JS?


A loop is a control structure used to repeat a block of code multiple times. Types include:

for loop

while loop

do...while loop

for...in loop (iterates over object properties)

for...of loop (iterates over iterable objects)

Q12. What are Functions in JS? Types of Functions?


A function is a block of reusable code. Types:

Named functions

Anonymous functions

Arrow functions (ES6)

Q13. What are Arrow Functions in JS?


Arrow functions provide a shorter syntax for writing functions and inherit the this value from the
enclosing context. Example:

408/411
js

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

Q14. What are Arrays in JS? How to Get, Add & Remove Elements?
Arrays store multiple values. Common operations:

Get: arr[index]

Add: push() , unshift()

Remove: pop() , shift()

Q15. What are Objects in JS?


An object is a collection of properties, each with a key-value pair. Example:

js

const person = {
name: "John",
age: 30
};

Q16. What is Scope in JavaScript?


Scope refers to the visibility and lifetime of variables. Types:

Global Scope: Variables declared outside any function.

Local Scope: Variables declared within a function.

Q17. What is Hoisting in JavaScript?

409/411
Hoisting is JavaScript’s behavior of moving declarations to the top of the scope during compile time.
Only the declaration is hoisted, not the initialization.

Q18. What is Error Handling in JS?


Error handling in JavaScript is done using try...catch...finally blocks to handle exceptions:

js

try {
// code that may throw an error
} catch (error) {
// handle the error
} finally {
// code that runs regardless of error
}

Q19. What is JSON?


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s easy to read and write
for humans and machines. Example:

json

{
"name": "John",
"age": 30
}

Q20. What is Asynchronous Programming in JS? What is its Use?


Asynchronous programming allows operations like file reading or API calls to be executed in parallel,
without blocking the execution of other code. It's used for handling tasks like fetching data from a
server.

410/411
These are the first 20 questions, but there are more detailed explanations available for all the topics
you've listed. Would you like to dive into more of them or focus on a specific one?

411/411

You might also like