Interview Cheatsheet

πŸ“„ HTML Basics

Semantic HTML Tags

Tag Purpose
<header> Introductory content, site branding, navigation
<nav> Major navigation links
<main> Main unique content (one per page)
<article> Self-contained content (blog post, comment)
<section> Thematic grouping of related content
<aside> Sidebar, related links, supplementary info
<footer> Page footer, copyright, related links
<figure> Self-contained illustration, diagram, photo
<figcaption> Caption for <figure>

Web Accessibility (a11y)

Key Principles

  • Perceivable: Content must be perceivable by users
  • Operable: Navigation via keyboard, no keyboard traps
  • Understandable: Content is clear and readable
  • Robust: Works with assistive technologies

Accessibility Checklist

  • alt text on all images
  • Proper heading hierarchy (h1 β†’ h6)
  • Form labels with <label> tags
  • aria-label for icon buttons
  • role attributes for custom components
  • Color contrast ratio β‰₯ 4.5:1
  • Keyboard navigation support
  • Focus indicators visible

HTML Forms

Input Type Description
text Single-line text input
password Password input (masked)
email Email address input with validation
number Numeric input with optional min/max
checkbox Multiple selection options
radio Single selection from a group
submit Submit the form data

Remember to use the correct form attributes like:

  • action: URL to send form data to
  • method: GET or POST for data submission

HTML5 New Features

  • New Semantic Elements: <header>, <footer>, <article>, <section>, <nav>
  • Audio and Video: <audio>, <video> tags for media playback
  • Canvas: <canvas> for drawing graphics via JavaScript
  • Local Storage: Web Storage API for storing data in the browser
  • Geolocation API: Access user's location with permission
  • Form Enhancements: New input types, validation, and attributes

Flashcards β€” HTML

What is the purpose of a semantic tag?
It gives meaning to content and improves accessibility and SEO.
Why is alt text important?
It helps screen readers describe images and improves accessibility.
What does ARIA stand for?
It stands for Accessible Rich Internet Applications.
What does ARIA help with?
It helps make custom UI components more accessible to assistive technologies.
Why use <section> instead of <div>?
A <div> is a generic container with no semantic meaning, while <section> groups related content that usually has a heading and gives structure to the page.
What is the difference between <article> and <section>?
An <article> is a self-contained piece of content that should still make sense on its own, while a <section> groups related content under a common theme.
What is <span> used for?
A <span> is an inline element mainly used to style or target part of a sentence or word without breaking the flow of text.
🟨 JavaScript (ES6+)

Async/Await vs Promises

Promises Async/Await
Chainable with .then/.catch Syntactic sugar over Promises, reads like sync code
Good for parallel flows (Promise.all) Good for sequential flows and readability
Must handle rejections with .catch Use try/catch for errors
Works in older environments with polyfills Requires async-capable runtime or transpile
// create 23 promises and await them
const tasks = Array.from({length:23}, (_,i) =>
  new Promise((res) => setTimeout(() => res(i+1), 10 + (i%5)*10))
);

// parallel with Promise.all
Promise.all(tasks).then(results => console.log('parallel results', results));

// sequential with async/await
async function runSequential(){
  const out = [];
  for(const t of tasks){
    out.push(await t);
  }
  console.log('sequential results', out);
}
runSequential();

Arrow Functions

Shorter syntax; lexical `this` binding.

const nums = [1,2,3];
const squares = nums.map(n => n*n);
const obj = {
  val: 10,
  getVal: () => this.val // `this` is lexical, not the object
};

let / const & Block Scope

`let` and `const` are block-scoped; `const` is immutable binding.

for(let i=0;i<3;i++){
  setTimeout(()=>console.log(i), 10); // prints 0,1,2
}
const a = {x:1};
a.x = 2; // allowed; binding immutable, properties mutable

Destructuring & Defaults

const [a,b=2] = [1];
const {name='anon'} = {};
function f({x=0,y=0} = {}){ return x+y }

Spread & Rest

const a = [1,2];
const b = [...a,3];
function sum(...nums){ return nums.reduce((s,n)=>s+n,0) }

Modules (import / export)

// module.js
export function add(a,b){ return a+b }

// main.js
import { add } from './module.js';
console.log(add(1,2));

Browser Storage

Use localStorage for data that should persist across browser sessions, and sessionStorage for temporary data that should disappear when the tab closes.

localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');

sessionStorage.setItem('step', '2');

Classes & Prototypes

class Animal{ constructor(name){ this.name = name } speak(){ return this.name } }
class Dog extends Animal{ bark(){ return 'woof' }}
const d = new Dog('Fido');

Map / Set

const s = new Set([1,2,2]);
const m = new Map([['k', 'v']]);
console.log(s.has(1), m.get('k'));

Coercions

let x = (5 == "5") // x = true
let y = (5 === "5") // y = false

Conversion


let y = (5 === "5") // y = false

Generators & Iterators

function* gen(){ yield 1; yield 2 }
const it = gen();
console.log(it.next().value);

Flashcards β€” JavaScript

Promise vs async/await: main difference?
async/await is syntactic sugar over Promises, making async code look synchronous; Promises provide methods like .then/.catch.
How do you handle multiple promises in parallel?
Use Promise.all (or Promise.allSettled) to run promises in parallel and await their combined result.
What is a closure?
A function that retains access to the lexical scope in which it was created, even after that scope has exited.
Explain event loop microtasks vs macrotasks.
Microtasks (Promises) run after the current task but before the next rendering; macrotasks (setTimeout) run later in the queue.
Difference between == and ===?
== performs type coercion before comparison; === checks strict equality without coercion.
What's lexical `this` in arrow functions?
Arrow functions do not have their own `this`; they inherit `this` from the surrounding lexical scope.
When to use Map vs Object?
Map preserves insertion order, accepts any key types, and has size propertyβ€”better for keyed collections than plain objects.
What are generators good for?
Generators allow pausing/resuming function execution and are useful for lazy sequences and implementing iterators.
How do modules differ from CommonJS require?
ES modules are statically analyzable and use `import`/`export`; CommonJS loads modules at runtime with `require`.
What is the difference between let, const, and var?
`var` is function-scoped and hoisted; `let` and `const` are block-scoped, with `const` being immutable binding.
What is the difference between null and undefined?
`undefined` means a variable has been declared but not assigned; `null` is an assignment value representing no value.
What is the difference between synchronous and asynchronous code?
Synchronous code runs sequentially, blocking further execution until complete; asynchronous code allows other operations to run while waiting for tasks to finish.
What is the difference between synchronous and asynchronous code?
Synchronous code runs sequentially, blocking further execution until complete; asynchronous code allows other operations to run while waiting for tasks to finish.
TypeScript

Basic Types

Type Example
number let age:number = 25;
string let name:string = "Izzy";
boolean let active:boolean = true;
array let nums:number[] = [1,2,3];
tuple let user:[string,number] = ["Izzy",54];
let age:number = 54;
let name:string = "Izzy";
let scores:number[] = [18,20];

Type vs Interface

type interface
Can describe primitives Objects only
Supports unions No unions
Supports intersections Can extend
More flexible Great for object contracts
interface User{
 id:number;
 name:string;
}

type Status =
"loading" | "success" | "error";

Optional & Readonly

interface User{
 id:number;
 name?:string;
 readonly email:string;
}

? optional property

readonly cannot be modified after creation.

Union Types

type Status =
"loading"
| "success"
| "error";

let state:Status = "loading";

Allows multiple possible types or values.

Generics

function identity<T>(value:T):T{
 return value;
}

identity(5);
identity("hello");

Reusable types that work with many data types.

any vs unknown vs never

Type Meaning
any Turns off type checking
unknown Must check type before use
never Function never returns
let value:unknown;

if(typeof value === "string"){
 console.log(value.length);
}

Type Assertions

const input =
document.getElementById("name")
as HTMLInputElement;

console.log(input.value);

Tells TypeScript the expected type.

Functions

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

Always type parameters and return values.

Promise<T>

interface User{
 id:number;
 name:string;
}

async function getUser():
Promise<User>{

 return {
  id:1,
  name:"Izzy"
 };

}

Promise<User> means the promise eventually resolves to a User.

React + TypeScript

type ButtonProps={
 title:string;
 onClick:()=>void;
}

function Button({
 title,
 onClick
}:ButtonProps){

 return (
  <button
   onClick={onClick}>
   {title}
  </button>
 );

}

const [user,setUser] =
useState<User|null>(null);

Flashcards β€” TypeScript

What is TypeScript?
A superset of JavaScript that adds static typing and compiles to JavaScript.
Difference between type and interface?
Both describe object shapes. Type is more flexible (unions, primitives, intersections). Interface is commonly used for object contracts and can be extended.
What is a union type?
A variable that can hold one of several types or literal values using |.
What does ? mean in an interface?
The property is optional.
What does readonly do?
Prevents modifying a property after the object has been created.
Difference between any and unknown?
any disables type checking. unknown requires checking the type before using the value.
What is never?
Represents values that never occur, typically functions that always throw or never finish.
What is Promise<User>?
A Promise that eventually resolves to a User object.
How do you type React props?
Create a type or interface describing the props and use it in the component parameter.
How do you type useState?
useState<User | null>(null) explicitly tells TypeScript the state type.

Interview Traps ⭐

Question Answer
type vs interface type is more flexible (unions, intersections, primitives). interface is ideal for describing object shapes and can be extended.
any vs unknown unknown is safer because TypeScript forces you to check the type before using it.
null vs undefined undefined means a variable hasn't been assigned. null is an intentional absence of value.
Promise<User> A Promise that eventually resolves to a User.
User[] An array of User objects.
User | null The value can either be a User object or null.
<T> A generic placeholder type used to make reusable functions and classes.

Flashcards β€” TypeScript Interview Traps

Why use TypeScript instead of JavaScript?
TypeScript adds static typing, catches errors at compile time, improves autocompletion, and makes large codebases easier to maintain.
Does TypeScript run in the browser?
No. TypeScript is transpiled into plain JavaScript before running in the browser.
What is the difference between an interface and an object?
An interface is a blueprint used only during compilation. An object is a real value that exists at runtime.
What is the difference between type and interface?
Both describe object shapes. Type is more flexible because it supports unions, primitives and intersections. Interfaces are commonly used for object contracts.
What is a generic?
A generic lets you write reusable code that works with many different types while keeping type safety.
What does <T> represent?
It is a generic type parameterβ€”a placeholder for a type that will be supplied later.
What is Promise<User>?
A Promise that eventually resolves to a User object.
Difference between any and unknown?
any disables all type checking. unknown requires checking the value before using it, making it much safer.
When would you use readonly?
When a property should never be modified after an object has been created.
What does ? mean after a property name?
It makes the property optional.
How do you type React component props?
Create a type or interface for the props and use it in the component parameter.
How do you type useState?
Example: const [user, setUser] = useState<User | null>(null);
What does User[] mean?
An array containing User objects.
What does User | null mean?
The value can either be a User object or null.
Why avoid using any?
Because it disables TypeScript's type checking, making it easier for bugs to slip into your code.
πŸ’» CSS Basics

CSS Selectors

Selectors are patterns used to select the elements you want to style. Common types include:

  • Type Selector: Selects elements by their tag name (e.g., div, p).
  • Class Selector: Selects elements with a specific class (e.g., .my-class).
  • ID Selector: Selects an element with a specific ID (e.g., #my-id).
  • Attribute Selector: Selects elements based on attributes (e.g., [type="text"]).
  • Pseudo-classes: Selects elements based on their state (e.g., :hover, :first-child).
  • Pseudo-elements: Selects and styles parts of an element (e.g., ::before, ::after).
/* Type Selector */
p {
  color: blue;
}       

        

css position

Position Description
static Default position; elements flow in the normal document flow.
relative Element is positioned relative to its normal position.
absolute Element is positioned relative to its nearest positioned ancestor.
fixed Element is positioned relative to the viewport and does not move when scrolled.
sticky Element toggles between relative and fixed, depending on the scroll position.
div {
  position: absolute;
  top: 10px;
  left: 20px;
}

CSS center a div

To center a div horizontally and vertically, you can use Flexbox or Grid:

/* Flexbox */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Full viewport height */
} 
/* Grid */
.container {
  display: grid;
  place-items: center;
  height: 100vh; /* Full viewport height */
}

CSS Box Model

The CSS box model describes the rectangular boxes generated for elements in the document tree and consists of:

  • Content: The actual content of the box, where text and images appear.
  • Padding: Clears an area around the content. The padding is transparent.
  • Border: A border that goes around the padding (if any) and content.
  • Margin: Clears an area outside the border. The margin is also transparent.
<div class="box-container">
  <div class="box">1</div>
  <div class="box">2</div>
  <!-- repeat for 23 boxes -->
</div>

.box-container { padding: 12px; border: 2px solid #1976d2; }
.box { width: 32px; height: 32px; margin: 4px; padding: 6px; border: 2px solid #1565c0; }

CSS Flexbox

Flexbox is a one-dimensional layout method for arranging items in rows or columns. Key properties include:

  • display: flex; - Defines a flex container.
  • flex-direction: - Row or column layout.
  • justify-content: - Aligns items horizontally.
  • align-items: - Aligns items vertically.
  • flex-wrap: - Allows items to wrap onto multiple lines.
  • Navigation bars vertical centering
  • Product Cards vertical stacking and spacing
<div class="flex-demo">
  <div class="box">1</div>
  <div class="box">2</div>
  <!-- repeat for 23 boxes -->
</div>

Navigation Bar


.flex-demo {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

Product Cards

nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

CSS Grid

CSS Grid is a two-dimensional layout system for creating complex layouts. Key properties include:

  • display: grid; - Defines a grid container.
  • grid-template-columns / grid-template-rows: - Defines the columns and rows of the grid.
  • grid-gap: - Sets the gap between rows and columns.
  • grid-column / grid-row: - Specifies how many columns or rows an item should span.
  • justify-items / align-items: - Aligns items within their grid area.
<div class="grid-demo">
  <div class="box">1</div>
  <div class="box">2</div>
  <!-- repeat for 23 boxes -->
</div>

.grid-demo {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
}

Flashcards β€” CSS

What is the difference between Flexbox and Grid?
Flexbox is for one-dimensional layouts (rows or columns), while Grid is for two-dimensional layouts (rows and columns).
What is the difference between padding and margin?
Padding is the space between the content and the border of an element, while margin is the space outside the border, separating the element from other elements.
What are the four parts of the box model?
Content, padding, border, and margin.
What is Flexbox best for?
Laying out items in one dimension, either rows or columns.
What is CSS Grid best for?
Creating two-dimensional layouts with rows and columns.
What does justify-content do in Flexbox?
It aligns items along the main axis (horizontally in a row, vertically in a column).
What does align-items do in Flexbox?
It aligns items along the cross axis (vertically in a row, horizontally in a column).
What is the difference between inline, block, and inline-block elements?
Inline elements do not start on a new line and only take up as much width as necessary. Block elements start on a new line and take up the full width available. Inline-block elements are like inline elements but can have width and height set.
What is the difference between relative, absolute, fixed, and sticky positioning?
Relative positions an element relative to its normal position. Absolute positions it relative to its nearest positioned ancestor. Fixed positions it relative to the viewport. Sticky toggles between relative and fixed based on scroll position.
What is the difference between a pseudo-class and a pseudo-element?
A pseudo-class selects elements based on their state (e.g., :hover, :first-child), while a pseudo-element selects and styles parts of an element (e.g., ::before, ::after).
What is the difference between em, rem, and px units?
em is relative to the font-size of the parent element. rem is relative to the font-size of the root element. px is an absolute unit representing pixels.
βš›οΈ React

React Update & Re-render Model

Mechanism What triggers the update? When does the component re-render? Typical useEffect dependency
useState setState(newValue) After the state value changes. [state]
useReducer dispatch(action) After the reducer returns a new state. [state] or [state.someProperty]
useContext The Provider's value changes. Every component consuming that Context re-renders. [context] or [context.someProperty]
Props The parent renders with different props. The child component re-renders. [props.name]
useEffect Nothing. It never starts a render. It does not trigger a render by itself. Depends on the dependency array.
Remember:

useEffect() runs after React has rendered and updated the DOM. It reacts to changes; it does not cause them (unless it calls setState()).

React Render Cycle

User action
⬇
setState() / dispatch() / Context changes
⬇
Component renders again
⬇
Virtual DOM comparison
⬇
DOM updated
⬇
Browser Paint
⬇
useEffect()

React vs Vanilla JavaScript

Vanilla JavaScript manipulates the DOM directly with methods like querySelector and addEventListener. React lets you describe the UI declaratively with components and state, and it updates the DOM efficiently when state changes.

When should you use useEffect?

Dependency Runs when...
[] Only once after mount
[count] Whenever count changes
[user] Whenever context/state reference changes
No dependency array After EVERY render

Triggers Re-render?

Action Re-render?
setState() βœ” Yes
dispatch() βœ” Yes
Context Provider changes βœ” Yes
Props change βœ” Yes
useEffect() ✘ No*

* Unless the effect itself calls setState().

Use useEffect for side effects such as fetching data, subscribing to events, timers, or syncing with browser APIs like localStorage. It is usually not the right tool for computing values from existing state during render.

Context vs Reducer

Context Reducer
Shares state Updates state
Avoids prop drilling Centralizes logic
Who can access? How does it change?

Props: Parent to Child

A parent component can own state and pass both values and callback functions to children through props. This is a common pattern for controlling behavior from a parent.

function Parent() {
  const [count, setCount] = useState(0);

  const handleReset = () => setCount(0);

  return (
    

Count: {count}

); } function Child({ count, onReset }) { return ; }

Class vs Functional Components

Class Component Functional Component
Uses lifecycle methods Uses hooks
Has this.state and this.setState() Uses useState() hook
More boilerplate code Simpler and more concise

useContext

useContext lets a component read values from a context without passing props through every level. It is helpful for shared data such as themes, authentication, or user settings.

const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  return (
    
      {children}
    
  );
}

function Header() {
  const { theme } = useContext(ThemeContext);
  return 

Current theme: {theme}

; }

Flashcards β€” React

What triggers a React re-render?
State changes, prop changes, and context updates typically trigger re-renders.
How is React different from vanilla JavaScript?
Vanilla JavaScript manipulates the DOM directly, while React uses declarative components and state to update the DOM efficiently.
When should you use useEffect?
Use it for side effects such as fetching data, subscriptions, timers, and browser API synchronization.
When would you choose props over useContext?
Use props for simple, direct data flow between a parent and a child. Use useContext for shared values that many components need without threading props through every level.
When does useEffect run?
After the component renders, and again when its dependencies change.
What is the difference between context and reducer?
Context shares state, while a reducer centralizes how state changes.
What is the main difference between class and functional components?
Class components use lifecycle methods and this.state; functional components use hooks and are usually simpler.
When would you choose a functional component over a class component?
Functional components are preferred for modern React when you want simpler logic and hooks-based state/effects.
What is the purpose of a key prop in a list?
It helps React identify which list items changed, were added, or removed, improving reconciliation.
What is the difference between controlled and uncontrolled components?
Controlled components have their state managed by React, while uncontrolled components manage their own state internally.
What is the difference between useState and useReducer?
useState is for simple state management, while useReducer is better for complex state logic and multiple state transitions.
What is the difference between useEffect and useLayoutEffect?
useEffect runs after the render is committed to the screen, while useLayoutEffect runs synchronously after all DOM mutations but before the browser paints.
What is the difference between React.memo and useMemo?
React.memo is a higher-order component that memoizes a component to prevent unnecessary re-renders, while useMemo is a hook that memoizes a value or computation within a component.
πŸ…°οΈ Angular

Angular Architecture

  • Components: UI building blocks with templates and logic.
  • Modules: Group related features and declarations.
  • Services: Shared logic, data access, and cross-component state.
  • Dependency Injection: Angular injects dependencies where needed.

Data Binding

Angular supports several binding types:

  • Interpolation: {{ value }}
  • Property binding: [src]="imageUrl"
  • Event binding: (click)="save()"
  • Two-way binding: [(ngModel)]
@Component({
  template: `<h2>{{ title }}</h2>`
})
export class DemoComponent {
  title = 'Angular';
}

Services & Dependency Injection

Services centralize reusable logic and are injected into components via Angular's DI container.

@Injectable({ providedIn: 'root' })
export class UserService {
  getUsers() { return ['Ada', 'Grace']; }
}

RxJS & Observables

RxJS lets Angular handle asynchronous streams with observables, operators, and subscriptions.

this.http.get<User[]>('/api/users').subscribe(users => {
  this.users = users;
});

Change Detection

Angular updates the UI based on change detection. Using ChangeDetectionStrategy.OnPush can improve performance by limiting checks.

@Component({
  selector: 'app-card',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: '

{{ name }}

' }) export class CardComponent { @Input() name = ''; }

Flashcards β€” Angular

What are Angular components responsible for?
They define the UI, behavior, and template for a specific part of the application.
What is dependency injection in Angular?
It is a design pattern where Angular provides dependencies to classes instead of having them create them manually.
What is the difference between interpolation and property binding?
Interpolation renders values into text, while property binding updates DOM properties such as src or disabled.
What are services used for?
Services are used to share logic, data access, and business rules across multiple components.
What is RxJS commonly used for in Angular?
It handles asynchronous data streams, HTTP requests, events, and reactive programming.
What does OnPush change detection do?
It reduces unnecessary checks by only updating the component when its inputs or events change.
node.js
Event Loop
⬇
Call Stack
⬇
Node APIs (fs, http, etc.)
⬇
Callback Queue
⬇
Microtask Queue (Promises)

Node.js Event Loop

The Node.js event loop is a mechanism that allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible.

  • Phases: Timers, I/O callbacks, idle/prepare, poll, check, close callbacks.
  • Microtasks: Promises and process.nextTick are executed after the current operation completes but before the event loop continues.
  • Non-blocking: Node.js uses an event-driven architecture to handle multiple connections concurrently without blocking the main thread.

Node.js Modules

Node.js uses the CommonJS module system, where each file is treated as a separate module.

  • require: Used to import modules.
  • module.exports: Used to export functions, objects, or values from a module.
  • ES Modules: Node.js also supports ES6 modules using import and export, but it requires the use of the .mjs extension or setting "type": "module" in package.json.

Node.js Streams

Streams are a way to handle reading/writing data in chunks, which is efficient for large data sets.

  • Readable Streams: Used for reading data (e.g., fs.createReadStream).
  • Writable Streams: Used for writing data (e.g., fs.createWriteStream).
  • Duplex Streams: Can be both readable and writable (e.g., net.Socket).
  • Transform Streams: A type of duplex stream that can modify or transform the data as it is read or written.
πŸ€– Agentic AI

What is Agentic AI?

Agentic AI refers to systems that can plan, act autonomously, and manage multi-step tasks using reasoning, tools, and memory.

  • Autonomy: Sets and pursues goals with minimal human input.
  • Planning: Breaks complex tasks into steps and sequences actions.
  • Tool Use: Leverages external tools (APIs, code execution, browsers).
  • Safety: Includes guardrails: human oversight, constraints, and verification.

Design Patterns

  • Planner + Executor: Separate high-level planning from action execution.
  • Loop with Verification: Plan β†’ Act β†’ Observe β†’ Verify β†’ Replan.
  • Tool Abstraction: Wrap external tools with stable interfaces and validation.

Quick Tips

  • Limit action scope and require confirmations for irreversible steps.
  • Log actions and decisions for auditability.
  • Use sandboxed environments for risky operations.

Flashcards β€” Agentic AI

Security

What is SQL injection?
SQL injection is a code injection technique that exploits vulnerabilities in an application's software by inserting malicious SQL statements into an entry field for execution. This can allow attackers to manipulate the database, retrieve sensitive data, or even modify or delete records.
Give an example of SQL injection?
An example of SQL injection is when a web application fails to properly sanitize user input, allowing an attacker to insert malicious SQL code. For instance, if a login form doesn't use parameterized queries, an attacker could enter the following in the username field:
' OR '1'='1
This would bypass authentication and potentially allow unauthorized access to the application.
How do you prevent SQL injection?
To prevent SQL injection, use parameterized queries or prepared statements, validate and sanitize user inputs, and follow the principle of least privilege when designing database access.
What is Cross-Site Scripting (XSS)?
Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. This can lead to unauthorized actions, data theft, or session hijacking.
Give an example of Cross-Site Scripting (XSS)?
An example of Cross-Site Scripting (XSS) is when a web application fails to properly sanitize user input, allowing an attacker to inject a malicious script. For instance, if a comment section on a website allows users to submit comments without escaping HTML, an attacker could submit a comment like:
<script>alert('XSS Attack!');</script>
When other users view the comment, the script executes in their browsers, potentially stealing cookies or performing other malicious actions.
How do you prevent Cross-Site Scripting?
To prevent Cross-Site Scripting (XSS), sanitize (escape) and validate user inputs, use Content Security Policy (CSP) headers, encode output when displaying user-provided data, and implement proper security measures in your web application. Set httpOnly and Secure flags on cookies to protect against session hijacking.
What is Cross-Site Request Forgery (CSRF)?
Cross-Site Request Forgery (CSRF) is an attack that tricks a user into performing unintended actions on a web application where they are authenticated. It exploits the trust that a site has in the user's browser, potentially leading to unauthorized state changes or data manipulation.
How do you prevent Cross-Site Request Forgery?
To prevent Cross-Site Request Forgery (CSRF), use anti-CSRF tokens, implement the SameSite cookie attribute, validate the origin of requests, and ensure that state-changing operations require explicit user confirmation.
Give an example of Cross-Site Request Forgery?
A common example is when a user is logged into their bank account and visits a malicious website. The malicious site could include a hidden form that submits a transfer request to the bank's server without the user's knowledge or consent.
What is the difference between Cross-Site Scripting and Cross-Site Request Forgery?
Cross-Site Scripting (XSS) involves injecting malicious scripts into web pages viewed by other users, while Cross-Site Request Forgery (CSRF) tricks a user into performing unintended actions on a web application where they are authenticated.
What is IDOR? What does it stand for?
IDOR stands for Insecure Direct Object Reference. It occurs when an application uses user-supplied input to access objects directly, without proper authorization checks.
Give an example of IDOR?
An example of IDOR is when a user can access another user's account information by simply changing the ID parameter in the URL, such as `https://example.com/user/123` to `https://example.com/user/456`.