Tech Knowledge Base

Quick lookup, concepts, recipes, troubleshooting, and interview practice flashcards

GitOllamaJavaScriptTypeScriptCSSReactAngularNode.jsPythonDatabasesSecurityAgentic AIInterview
Git

terminal

Command Function
git init Initialize a new Git repository.
git clone <repository_url> Clone an existing repository.
git status Display working tree status and staged changes.
git add <file> Stage a specific file for commit.
git add . Stage all modified and new files.
git commit -m "message" Create a commit with a message.
git log Show commit history.
git log --oneline Show compact commit history.
git diff Show unstaged changes.
git diff --staged Show staged changes.
git branch List local branches.
git branch <your_branch_name> Create a new branch.
git checkout <your_branch_name> Switch to a branch.
git switch <your_branch_name> Switch to a branch (modern command).
git checkout -b <your_branch_name> Create and switch to a new branch.
git switch -c <your_branch_name> Create and switch to a new branch (modern command).
git merge <your_branch_name> Merge a branch into the current branch.
git rebase <your_branch_name> Reapply commits on top of another branch.
git remote -v List configured remote repositories.
git fetch Download changes from remotes without merging.
git pull Fetch and merge remote changes.
git push Push local commits to the remote repository.
git push -u origin <your_branch_name> Push a new branch and set upstream tracking.
git stash Temporarily save uncommitted changes.
git stash pop Restore the most recent stashed changes.
git reset --hard HEAD Discard all local uncommitted changes.
git revert <commit_hash> Create a new commit that reverses a previous commit.
git rm <file> Remove a file and stage the deletion.
git mv <old_file> <new_file> Rename or move a file.
git tag List tags.
git tag <tag_name> Create a new tag.

I find out I have been working on the wrong git branch 😭 How can I move all exitsting uncommited changes to my other branch?

git stash
git checkout <other_branch>
git stash pop
           or
            
git switch <other_branch>
            
or
git switch <other_branch>
            

I want to push to 2 remote urls. How can I rename the existing remote and add it using a different remote name?

git remote set-url origin <https://huggingface.co..... >
git remote add hf <https://huggingface.co.....> 
git remote add github <https://github.com.....>
git push hf main
then use the remote name when pushing:
git push hf main
            

I want to push my new feature to production. I am using Continuous deployment. Anything pushed to main is automatically published. What is the safe flow?

The standard industry practice for Continuous Deployment (GitHub Flow). No manual backup branches, no direct pushes to main, and all testing happens before production.

unsafe flow ❌

  1. on the feature branch let's say 'dev' add your files, commit and push to origin dev
  2. checkout to the back up branch and , pull and merge the main branch into to and push it to origin backup
  3. on the production branch let's say 'main' pull and merge dev into main, commit and push to origin main
// check everything is ready to push 
          and push to the remote
git checkout dev
git pull
git push origin dev
// checkout to the backup branch, 
// this is the fall back branch. 
// merge the existing production state into it 
git checkout backup
git pull
git merge main
git push origin backup
// checkout to the production branch
// merge the new feature 
// from the feature branch into it
git checkout main
git pull 
git merge dev
git push origin main
        

safe flow ✅

  1. Update your local feature branch with the latest production code to catch and fix conflicts early.
  2. Push your feature branch to the remote repository and open a Pull Request (PR) into main.
  3. Let automated tests (CI) run on the PR, get a review, and click "Merge" on GitHub to automatically deploy.
// 1. Bring production changes into dev and test locally
// be ready to resolve merge issues if someone pushed new changes.
git checkout dev
git pull origin main
# RESOLVE CONFLICTS - RUN YOUR TESTS LOCALLY
git push origin dev

// 2. Open a Pull Request on GitHub (dev -> main)
// new pull request
// on the first drop down (choose a base ref): main
// on the second one(choose a head ref) : dev 
// Do NOT merge in the terminal. Let GitHub run CI tests.

// 3. Click "Merge" on GitHub (once tests pass). 
// automatically builds and deploys to production.

// 4. bug ? use your hosting platform dashboard
// to roll back to the previous stable build artifact.
        

Disclaimer: Use these commands at your own discretion and always check what a command will do before running it. I’m not responsible for any loss or damage resulting from their use.

↑ Back to top
Ollama

terminal

Command Purpose
ollama run[Model] checkes if model is downloaded and downloads it if not - starts the Ollama server also switches to another model
/? shows available commands and options
/bye exits the chat
ollama pull[Model] Download a model from the Ollama Hub without starting the server
ollama list displays a list of all models
rm [Model] erases a model from the local storage
ollama serve starts the Ollama server in the background
http://localhost:11434/ access the Ollama server via HTTP: "ollama is running"
curl http://localhost:11434/api/generate -d '{"model": "qwen2:7b", "prompt": "Why is the sky blue?", "stream": false}' curl prompts the Ollama server to generate a response
↑ Back to top
JavaScript

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);
↑ Back to top
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);
↑ Back to top
CSS

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;
}
↑ Back to top
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}

; }
↑ Back to top
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 = ''; }
↑ Back to top
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.
↑ Back to top
🐍 Python

Python terminal commands

prompt Purpose
pip --version which version
pip install ollama install a ollama to bridge with python
pip show ollama check the version of ollama installed
🗄️ Databases

SQL vs MongoDB

SQL MongoDB
Relational database Document-oriented NoSQL database
Uses structured query language (SQL) Uses a flexible, JSON-like query language
Data is stored in tables with rows and columns Data is stored in collections of documents (BSON format)
Schema is predefined and rigid Schema is dynamic and flexible
Supports complex joins and transactions Limited support for joins; transactions are supported but less common

CRUD Operations

Operation SQL MongoDB
Create INSERT INTO table_name (column1, column2) VALUES (value1, value2); db.collection.insertOne({ field1: value1, field2: value2 });
Read SELECT * FROM table_name WHERE condition; db.collection.find({ field: value });
Update UPDATE table_name SET column1 = value1 WHERE condition; db.collection.updateOne({ field: value }, { $set: { field: newValue } });
Delete DELETE FROM table_name WHERE condition; db.collection.deleteOne({ field: value });

Joins

SQL databases support joins to combine data from multiple tables based on related columns. MongoDB does not have traditional joins, but it can perform similar operations using the aggregation framework or by embedding related data within documents.

MongoDB's $lookup stage is used to perform left outer joins between collections.

Join Type SQL MongoDB
INNER JOIN SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id; db.collection.aggregate([{ $lookup: { from: "otherCollection", localField: "field1", foreignField: "field2", as: "joinedData" } }]);
Security

Security, APIs, and Web Development

Security is critical in web development to protect data, users, and systems from malicious attacks.

  • SQL Injection: Attackers inject malicious SQL queries to manipulate databases.
  • Cross-Site Scripting (XSS): Attackers inject scripts into web pages viewed by others.
  • Cross-Site Request Forgery (CSRF): Tricks users into performing actions they didn't intend.
  • IDOR: Insecure Direct Object Reference allows unauthorized access to objects.

Best Practices

  • Use parameterized queries to prevent SQL injection.
  • Sanitize and validate user inputs to prevent XSS.
  • Implement anti-CSRF tokens and SameSite cookies.
  • Perform proper authorization checks to avoid IDOR.

Best HTTP status codes

  • 200 OK: The request was successful.
  • 201 Created: The request was successful and a new resource was created.
  • 400 Bad Request: The server could not understand the request due to invalid syntax.
  • 401 Unauthorized: The client must authenticate itself to get the requested response.
  • 403 Forbidden: The client does not have access rights to the content.
  • 404 Not Found: The server can not find the requested resource.
  • 500 Internal Server Error: The server has encountered a situation it doesn't know how to handle.
↑ Back to top
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.
↑ Back to top
🎯 Interview & 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

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.

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.
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.
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.
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

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

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

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.

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`.
IDOR vs BOLA
IDOR (Insecure Direct Object Reference) occurs when an application uses user-supplied input to access objects directly, without proper authorization checks. BOLA (Broken Object Level Authorization) is a more specific type of IDOR where the authorization check is bypassed at the object level. In essence, BOLA is a subset of IDOR for API endpoints.
what is p95/p99?
P95 and P99 are performance metrics that represent the 95th and 99th percentiles of response times in a system. P95 indicates that 95% of requests are faster than this time, while P99 indicates that 99% of requests are faster. These metrics help identify outliers and assess system performance under load.
explain the difference between 401 and 403?
401 Unauthorized indicates that the user is not authenticated, while 403 Forbidden indicates that the user is authenticated but does not have permission to access the requested resource.
explain the difference between 400 and 500?what typically causes each?
400 Bad Request indicates that the client sent a malformed request, while 500 Internal Server Error indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
explain POST vs PUT vs PATCH
POST is used to create a new resource, PUT is used to update an existing resource, and PATCH is used to make partial updates to an existing resource.
In which case is it dangerous to use PUT instead of PATCH? and why?
Using PUT instead of PATCH can be dangerous when you want to update only specific fields of a resource. PUT replaces the entire resource with the new data, which can lead to unintentional loss of data if not all fields are provided. PATCH, on the other hand, allows for partial updates, modifying only the specified fields while leaving the rest of the resource intact.
is POST idempotent? and why?
POST is not idempotent because each request creates a new resource. If you make the same POST request multiple times, it will create multiple resources with different IDs.
What is a parameterized query? give an example.
A parameterized query is a query that uses parameters to replace values, preventing SQL injection attacks. For example, instead of concatenating user input directly into a query string, you would use a parameterized query like `SELECT * FROM users WHERE id = ?` and pass the user input as a parameter.
How would you validate the input of a client review form to prevent XSS attacks?Give an example of code escaping a <script> tag.
To prevent XSS attacks, you should sanitize user input by escaping HTML characters and using a whitelist of allowed tags and attributes.