Quick Answers
Clear, practical answers to the most-asked developer questions, with code examples and video explanations.
How do you undo the last commit in Git?
Keep or discard your changes while rolling back the most recent commit using git reset or git revert.
How do you create and switch to a new branch in Git?
Create a branch and check it out in one step with git switch -c or the older git checkout -b.
What is the difference between git merge and git rebase?
Merge preserves full history with a merge commit; rebase replays commits on top of another branch for a linear history.
How do you resolve a merge conflict in Git?
Identify conflicting files, edit the conflict markers, stage the resolved files, and complete the merge.
How do you stash uncommitted changes in Git?
Temporarily shelve work-in-progress changes with git stash so you can switch branches with a clean working tree.
How do you delete a branch in Git?
Delete a local branch with git branch -d and a remote branch with git push origin --delete.
How do you amend the last commit message in Git?
Fix a typo or update the last commit message with git commit --amend before pushing.
How do you view commit history in Git?
Use git log with various flags to browse, filter, and format your repository's commit history.
How do you cherry-pick a commit in Git?
Copy a specific commit from one branch to another without merging the whole branch using git cherry-pick.
What is the difference between git fetch and git pull?
git fetch downloads remote changes without applying them; git pull fetches and immediately merges (or rebases) into your current branch.
How does .gitignore work in Git?
A .gitignore file tells Git which files and folders to never track - useful for build outputs, secrets, and editor files.
How do you create and use tags in Git?
Tags mark specific commits as releases or milestones. Annotated tags include a message and are the standard for versioning.
How do you squash multiple commits into one in Git?
Use interactive rebase (git rebase -i) to combine several WIP commits into a single, clean commit before merging.
How do you center a div in CSS?
Three modern ways to horizontally and vertically center a div: Flexbox, CSS Grid, and the classic margin auto trick.
What is the CSS box model?
Every HTML element is a rectangular box made of content, padding, border, and margin understanding these four layers is fundamental to layout.
What is the difference between position relative, absolute, and fixed?
Relative keeps the element in normal flow; absolute removes it from flow and positions relative to its nearest positioned ancestor; fixed sticks to the viewport.
How do CSS custom properties (variables) work?
Define reusable values with --name syntax on :root, then reference them anywhere with var(--name).
How does z-index work in CSS?
z-index controls stacking order, but only works on positioned elements inside the same stacking context.
How does Flexbox work in CSS?
Flexbox is a 1D layout model - set display:flex on a container to control how its children are arranged along a main axis and a cross axis.
How does CSS Grid work?
CSS Grid is a 2D layout system - define rows and columns on a container, then place children into specific grid cells or let them auto-flow.
What is the difference between px, em, rem, %, vh, and vw in CSS?
px is absolute; em is relative to the parent font-size; rem is relative to the root font-size; % depends on context; vh/vw are percentages of the viewport.
How do CSS media queries work?
Media queries apply CSS rules only when certain conditions are met - most commonly the viewport width - enabling responsive designs.
What is the difference between CSS transitions and animations?
Transitions animate between two states triggered by a change (e.g. hover). Animations use keyframes to define multi-step sequences that can run automatically.
How does CSS specificity work?
Specificity determines which CSS rule wins when multiple rules target the same element. It is calculated as a score: inline > ID > class > element.
What is the difference between <div> and <span>?
<div> is a block-level container that starts on a new line; <span> is an inline container that flows with text.
What is the difference between id and class in HTML?
id is unique only one element per page; class is reusable any number of elements can share it.
What is semantic HTML and why does it matter?
Semantic elements describe the meaning of content they help search engines, screen readers, and developers understand page structure.
How do you open a link in a new tab in HTML?
Add target="_blank" to an <a> tag, and always pair it with rel="noopener noreferrer" for security.
What should you put in the alt attribute of an image?
Describe what the image conveys in context. Use an empty alt="" for decorative images so screen readers skip them.
How do HTML forms work?
An HTML form collects user input and submits it to a server. Key attributes are action (where to send), method (GET or POST), and the name attributes on inputs.
What are HTML data attributes?
data-* attributes store custom data on HTML elements that JavaScript can read without using hidden inputs or class name hacks.
What is the difference between defer and async on a <script> tag?
Both download scripts without blocking HTML parsing. defer runs after parsing in document order; async runs immediately when downloaded, in any order.
What is the difference between var, let, and const in JavaScript?
var is function-scoped and hoisted; let and const are block-scoped. Use const by default, let when you need to reassign, and avoid var.
What is the difference between == and === in JavaScript?
=== is strict equality types must match. == is loose equality JavaScript coerces types before comparing, which causes surprises.
How does async/await work in JavaScript?
async functions always return a Promise; await pauses execution until a Promise resolves, letting you write async code that reads like synchronous code.
What is a closure in JavaScript?
A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished executing.
How do map, filter, and reduce work in JavaScript?
map transforms each element, filter keeps elements that pass a test, and reduce accumulates all elements into a single value.
How do you deep copy an object in JavaScript?
Use structuredClone() for deep copies in modern environments. For shallow copies, use the spread operator or Object.assign().
How does try/catch/finally work in JavaScript?
try runs code that might throw; catch handles the error; finally always runs regardless of outcome useful for cleanup.
What is the difference between arrow functions and regular functions in JavaScript?
Arrow functions have no own `this`, `arguments`, or `prototype`. Regular functions bind their own `this` at call time.
What is the JavaScript event loop?
The event loop is how JavaScript handles asynchronous code - it picks callbacks from a queue and runs them one at a time on a single thread.
How does destructuring work in JavaScript?
Destructuring unpacks values from arrays or properties from objects into distinct variables in a single expression.
What are the spread and rest operators in JavaScript?
Both use ... but do opposite things: spread expands an iterable into individual elements; rest collects multiple elements into an array.
How do Promises work in JavaScript?
A Promise represents a value that is not yet available. It has three states: pending, fulfilled, or rejected. Chain .then() and .catch() to handle the result.
What is the difference between null and undefined in JavaScript?
undefined means a variable has been declared but not assigned a value; null is an intentional explicit assignment meaning "no value".
How do optional chaining (?.) and nullish coalescing (??) work?
?. safely accesses nested properties without throwing if an intermediate value is null or undefined. ?? provides a fallback only for null/undefined.
How do ES modules (import/export) work in JavaScript?
ES modules let you split code into files using export to expose values and import to consume them. Named exports and default exports work differently.
What is the difference between a list and a tuple in Python?
Lists are mutable (changeable); tuples are immutable (fixed). Use tuples for data that should not change and wherever a hashable sequence is needed.
How do list comprehensions work in Python?
A concise one-line syntax for building a new list by transforming or filtering another iterable replaces most simple for-loop patterns.
What is a decorator in Python?
A decorator is a function that wraps another function to add behaviour before or after it runs applied with the @ syntax.
How do you handle exceptions in Python?
Use try/except to catch specific exceptions, else for code that runs only on success, and finally for cleanup.
How do f-strings work in Python?
f-strings (formatted string literals) let you embed expressions directly in strings using curly braces the clearest and fastest string interpolation in Python.
What are generators and yield in Python?
A generator function uses yield instead of return to produce values one at a time, pausing execution between each - enabling lazy, memory-efficient iteration.
What are *args and **kwargs in Python?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict - both allow functions to accept variable numbers of arguments.
What is a context manager in Python?
A context manager (used with the `with` statement) ensures setup and cleanup code always run, even if an exception occurs - most commonly used for files, locks, and connections.
What are lambda functions in Python?
A lambda is an anonymous one-expression function defined inline. It is useful for short callbacks passed to functions like map(), filter(), and sorted().
What are dataclasses in Python?
The @dataclass decorator auto-generates __init__, __repr__, and __eq__ for a class based on its annotated fields - less boilerplate than writing them manually.
What is the difference between interface and type in TypeScript?
Both describe object shapes, but interfaces are extendable with declaration merging; type aliases are more flexible and work for unions, primitives, and tuples.
What is the difference between unknown and any in TypeScript?
any disables type checking entirely; unknown is the type-safe alternative you must narrow the type before using it.
How do generics work in TypeScript?
Generics let you write reusable code that works with any type while still being type-safe like a type parameter you fill in at the call site.
What are TypeScript utility types?
Utility types are built-in generic types that transform existing types - Partial, Required, Pick, Omit, Readonly, Record, and more are available out of the box.
How do enums work in TypeScript?
Enums define a set of named constants. TypeScript supports numeric and string enums - but const enums and union types are often better alternatives.
What is type narrowing in TypeScript?
Type narrowing is how TypeScript refines a broad type to a more specific one inside conditional blocks using typeof, instanceof, in, or custom type guards.
What are discriminated unions in TypeScript?
A discriminated union is a union of types that each share a literal "discriminant" field - TypeScript uses that field to narrow the type automatically.
What does "as const" do in TypeScript?
as const freezes a value's type to its most specific literal types, making all values readonly and preventing TypeScript from widening them to general types like string or number.
What is the difference between useState and useEffect in React?
useState stores and updates component state that drives re-renders; useEffect runs side effects (data fetching, subscriptions) after renders.
What is the difference between props and state in React?
Props are data passed from a parent to a child (read-only in the child); state is data owned and managed by the component itself.
What is the key prop in React and why does it matter?
The key prop helps React identify which list items changed, were added, or removed using array index as key causes subtle bugs.
What is the virtual DOM in React?
The virtual DOM is an in-memory representation of the UI. React diffs it against the previous version and only applies the minimal set of real DOM updates needed.
What are useCallback and useMemo in React?
useCallback memoizes a function reference; useMemo memoizes a computed value. Both skip re-computation when their dependencies have not changed.
What is the useRef hook in React?
useRef returns a mutable ref object that persists across renders without causing re-renders - used for accessing DOM nodes and storing mutable values.
How does React Context and useContext work?
React Context lets you pass data through the component tree without prop drilling. Create a context, wrap with a Provider, and consume with useContext.
What is the difference between controlled and uncontrolled components in React?
Controlled components store form input values in React state; uncontrolled components let the DOM manage the value and read it via a ref.
What are database transactions and why do they matter?
A transaction groups multiple SQL statements into a single atomic unit - either all succeed (COMMIT) or all are undone (ROLLBACK), ensuring data consistency.
What are window functions in SQL?
Window functions perform calculations across a set of related rows without collapsing them into groups - like aggregate functions but each row keeps its identity.
How does CASE WHEN work in SQL?
CASE WHEN is SQL's if/else expression - it evaluates conditions and returns a value for the first one that matches, or a default ELSE value.
What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only matching rows from both tables; LEFT JOIN returns all rows from the left table plus any matches from the right.
What is the difference between WHERE and HAVING in SQL?
WHERE filters rows before grouping; HAVING filters groups after GROUP BY. You cannot use aggregate functions in WHERE.
What is a database index and why does it matter?
An index is a data structure that lets the database find rows quickly without scanning the entire table like a book's index vs reading every page.
What is a CTE and how does it differ from a subquery?
A CTE (WITH clause) names a temporary result set for readability and reuse; a subquery is anonymous and embedded inline.
What is a Large Language Model (LLM)?
An LLM is a neural network trained on vast amounts of text to predict and generate human-like language - the technology behind ChatGPT, Claude, and Gemini.
What is the difference between AI, ML, and deep learning?
AI is the broad goal of machine intelligence; ML is a subset that learns from data; deep learning is a subset of ML using multi-layer neural networks - each is nested inside the previous.
What are tokens in AI language models?
Tokens are the chunks that an LLM reads and generates - roughly 3/4 of a word on average. Token count determines cost, speed, and whether your text fits in the context window.
What is prompt engineering?
Prompt engineering is the practice of crafting and structuring inputs to an LLM to reliably get the quality, format, and accuracy of output you need.
What is RAG (Retrieval-Augmented Generation)?
RAG is an architecture that lets an LLM answer questions using your own documents - retrieve relevant chunks, inject them into the prompt, then generate an answer grounded in that data.
What is the difference between fine-tuning and prompt engineering?
Prompt engineering guides a model at runtime with instructions; fine-tuning trains a new model checkpoint on your examples to bake in behaviour permanently - far more expensive but more consistent.
What are embeddings in AI?
Embeddings are numerical vector representations of text (or images, audio) where semantic similarity maps to geometric closeness - the engine behind search, recommendation, and RAG.
What is a vector database?
A vector database stores embeddings and enables fast approximate nearest-neighbour search - finding the most semantically similar items to a query vector at scale.
What is temperature in AI language models?
Temperature controls how random or deterministic a model's output is - low values (0–0.3) give focused, consistent answers; high values (0.7–1.5) give more varied, creative ones.
What is a context window in LLMs?
The context window is the maximum amount of text an LLM can see at once - it includes the system prompt, conversation history, retrieved documents, and the response being generated.
What is AI hallucination and how do you reduce it?
Hallucination is when an LLM confidently generates false information - invented facts, fake citations, or incorrect code. It is a fundamental property of how LLMs work, not a bug you can fully eliminate.
What is zero-shot, one-shot, and few-shot prompting?
These terms describe how many examples you include in your prompt - zero examples, one example, or a few (2–10). More examples help the model match the pattern you want.
What is an AI agent?
An AI agent is an LLM-powered system that can reason, plan, and take actions - calling tools, browsing the web, running code, or reading files to accomplish a goal autonomously.
What is function calling / tool use in LLMs?
Function calling lets an LLM request the execution of a function you define - the model outputs a structured JSON call with arguments, you run the function, and feed the result back for the model to use.
What is a transformer and how does it power LLMs?
The transformer is the neural network architecture behind all modern LLMs. Its key innovation - self-attention - lets every token in a sequence relate to every other token simultaneously, enabling parallel training on massive datasets.
How do you get structured JSON output from an LLM?
Use response_format with json_object or json_schema mode to force valid JSON output from an LLM. Pair it with a clear schema in the system prompt and TypeScript types for safe parsing.
What are system, user, and assistant roles in AI chat?
Chat APIs use three message roles: system sets the AI's behaviour and constraints, user contains the human's messages, and assistant contains the AI's previous replies. Together they form the conversation history.
What is multimodal AI and how do vision models work?
Multimodal AI processes more than one type of input such as text and images together. Vision-language models like GPT-4o and Claude can read screenshots, diagrams, and photos and reason about them.
How do you reduce AI API costs in production?
Reduce AI costs by choosing the right model for each task, caching repeated prompts, batching requests, compressing context, and setting output token limits.
How do you run an LLM locally with Ollama?
Ollama lets you download and run open-weight LLMs like LLaMA 3, Mistral, and Gemma on your own machine. It exposes an OpenAI-compatible API so your existing code works without changes.
What is RLHF and how does it make LLMs helpful?
RLHF (Reinforcement Learning from Human Feedback) is the training technique that turns a raw text predictor into a helpful, safe, instruction-following assistant by using human preference data as a reward signal.
What is semantic search and how is it different from keyword search?
Keyword search matches exact words in a query; semantic search matches meaning, so it finds relevant results even when no words overlap. Embeddings are what make semantic search possible.
What is MCP (Model Context Protocol)?
MCP is an open standard by Anthropic for connecting LLMs to external tools and data sources through a common interface. It lets AI assistants read files, query databases, and call APIs without custom integration code per tool.
How does streaming work with LLM APIs?
Streaming delivers tokens to the client as they are generated rather than waiting for the complete response. It makes AI responses feel instant and enables progressive rendering in chat UIs.
How do you handle rate limits and retries with AI APIs?
AI APIs enforce per-minute and per-day token/request limits. Handle them with exponential backoff retries, request queues, and model fallbacks so rate limit errors never reach your users.
What is a neural network?
A neural network is a function approximator made of layers of weighted connections. Weights are adjusted during training to map inputs to correct outputs. All modern AI including LLMs are built from neural networks.
What is prompt injection and how do you prevent it?
Prompt injection is an attack where malicious content in user input or retrieved data overrides your system prompt instructions, causing the AI to ignore safety rules or exfiltrate data.