An Angular service is used to share business logic or data between components. Instead of repeating the same logic everywhere, you put it in a service. Real-life example: a shared power socket—multiple devices use the same source instead of each having their own generator.
Interview Flashcards & Mock Mode
Practice with 3D flip cards, voice reader, and timed interview simulations.
CodeShot.in — Daily Challenges
60-second in-browser coding micro-challenges to sharpen syntax and problem-solving speed.
What is a service in Angular and why do we use it?
What is lazy loading in Angular and why is it useful?
Lazy loading means loading Angular modules only when they are needed instead of loading everything upfront. It’s like opening apps on your phone only when you tap them. This reduces initial load time and improves performance in large applications.
How do you implement lazy loading in Angular?
Lazy loading is implemented using Angular routing with loadChildren. Routes are configured so that modules load only when the user navigates to them.
When should you avoid lazy loading?
Lazy loading should be avoided for very small applications or core features that are always needed, because it may add unnecessary complexity and extra network calls.
What is a pipe in Angular?
A pipe transforms data in Angular templates without changing the underlying value. It’s like applying a filter on a photo—it changes how it looks, not the photo itself.
What is the difference between pure and impure pipes?
Pure pipes run only when input values change, making them performant. Impure pipes run on every change detection cycle and should be used carefully.
What is Change Detection in Angular and how does it work?
Change Detection is Angular's mechanism to detect when component data has changed and update the DOM accordingly. By default, Angular checks every component on every event. It's like a security guard scanning every person—thorough but slow for large apps. Using OnPush strategy tells Angular to check only when inputs change.
What is OnPush change detection strategy?
OnPush tells Angular to only run change detection when the component's input references change or an event triggers within the component. It significantly improves performance in large applications.
How does ChangeDetectorRef help in Angular?
ChangeDetectorRef lets you manually control change detection—triggering it explicitly or detaching it to prevent unnecessary checks. Useful in real-time data scenarios where you want fine-grained control.
What is the difference between Promise and Observable in Angular/Node.js?
A Promise handles a single future value and executes immediately. An Observable handles a stream of values over time and is lazy—it only executes when subscribed to. Think of a Promise as a one-time food delivery and an Observable as a subscription meal service that keeps delivering.
Can you cancel an Observable but not a Promise?
Yes. Observables can be unsubscribed, effectively cancelling them. Promises cannot be cancelled once started. This makes Observables more flexible for scenarios like search-as-you-type where old requests should be dropped.
How do you prevent SQL Injection and when are prepared statements not enough?
Prepared statements (parameterized queries) completely prevent SQL injection for data values because the database engine parses the SQL template structure separately from user input parameters.
However, prepared statements cannot parameterize SQL identifiers (such as table names, column names, or ASC/DESC order directions). To secure dynamic identifiers, you must use strict whitelist validation.
What is the CSS Box Model?
The CSS Box Model describes how every element on a page is a box made up of content, padding, border, and margin. Understanding it is essential for layout. Think of it like a framed photo—content is the photo, padding is the white space inside the frame, border is the frame, and margin is the gap between frames on the wall.
What is the difference between box-sizing: content-box and border-box?
content-box (default) calculates width excluding padding and border, often causing layout surprises. border-box includes padding and border in the width, making sizing more predictable. Most modern projects use border-box globally.
What is the difference between SQL and NoSQL databases?
SQL databases use structured tables with fixed schemas, ideal for relational data. NoSQL databases store data in flexible formats like documents, key-value pairs, or graphs. SQL is like a spreadsheet—rigid but consistent. NoSQL is like a filing cabinet—flexible but less structured.
What is the Singleton design pattern?
Singleton ensures only one instance of a class exists across the application. It’s like a shared printer in an office—everyone uses the same one instead of creating new printers.
What problems can Singleton cause?
Singletons can cause issues with unit testing, hidden dependencies, and tight coupling. Overusing them can make applications harder to maintain.
What is a namespace in .NET and why do we use it?
A namespace is used to organize related classes and avoid naming conflicts. Think of it like folders on your laptop—two files can have the same name as long as they are in different folders. In real projects, namespaces help keep code clean, readable, and manageable when applications grow large.
What is the difference between a class and an interface in .NET?
A class is something you can create an object from and it can contain implemented methods, properties, and fields. An interface is a contract—it only declares what methods a class must implement. Real-world analogy: a class is a car you can drive, while an interface is the rulebook that says every car must have brakes and steering.
What is dependency injection in .NET and why is it useful?
Dependency Injection means giving an object its dependencies from the outside instead of creating them inside the class. Think of it like ordering food from a restaurant instead of cooking everything yourself. It makes code loosely coupled, easier to test, and easier to maintain.
What is LINQ in .NET and why do developers use it?
LINQ allows you to query collections in C# using SQL-like syntax. For example, filtering a list of users without writing loops. It’s like using Google search instead of manually scanning every page of a book—cleaner, readable, and less error-prone.
How do you handle environment configuration in Node.js or .NET?
Environment configuration separates settings for development, testing, and production. For example, using .env files in Node.js or appsettings.json in .NET. It’s like having different modes on your phone—silent at work, loud at home—same phone, different behavior.
What is async/await in .NET and how does it improve application responsiveness?
Async/await allows methods to run without blocking the main thread while waiting for long-running tasks like API calls or database queries. It’s like ordering food at a restaurant—you don’t stand in the kitchen waiting; you sit and relax until the food arrives. In web apps, this keeps the UI responsive and allows the server to handle more requests.
What happens if you use async without await?
If you use async without await, the method runs asynchronously but you don’t wait for its result. This can lead to unexpected behavior, like code continuing before the task is finished. It’s like ordering food and leaving the restaurant without waiting to receive it.
Does async/await improve performance or just responsiveness?
Async/await mainly improves responsiveness and scalability, not raw performance. It allows better use of threads, especially in I/O operations, but CPU-bound tasks won’t run faster just because they are async.
What are extension methods in .NET?
Extension methods allow you to add new methods to existing classes without modifying their source code. It’s like installing an app to add features to your phone instead of changing the hardware.
What are limitations of extension methods?
Extension methods cannot access private members of a class and do not truly modify the class—they are resolved at compile time. Overuse can also make code harder to understand.
What is the Repository Pattern in .NET?
The Repository Pattern abstracts the data access layer, separating business logic from database operations. It's like a librarian—you ask for a book by title and they handle finding it. Your code doesn't care if data comes from MySQL, MongoDB, or a file.
What is the difference between Repository Pattern and Unit of Work?
Repository handles data operations for a single entity. Unit of Work coordinates multiple repositories in a single transaction, ensuring all changes are committed or rolled back together.
What is Git branching and why is it important in team development?
Branching lets developers work on features or fixes in isolation without affecting the main codebase. It's like working on a copy of a document—your changes don't overwrite the original until you're ready to merge.
What is the difference between git merge and git rebase?
Merge combines branches and keeps the full history. Rebase rewrites commit history to make it linear and cleaner. Merge preserves context, rebase keeps a tidy log. Teams choose based on their workflow preferences.
What is a pull request and why is it used?
A pull request is a request to merge your branch into the main branch. It triggers code review, discussion, and approval before changes land in production. It's a quality gate that keeps the codebase stable.
What are HTTP status codes and why are they important in REST APIs?
HTTP status codes indicate the result of a request. 2xx means success, 4xx means client error, 5xx means server error. They're like traffic lights—green means go, red means stop. Using correct codes helps API consumers handle responses properly.
What is the difference between 401 and 403?
401 Unauthorized means the user is not authenticated—they need to log in. 403 Forbidden means they are authenticated but don't have permission. Think of 401 as 'Who are you?' and 403 as 'I know who you are, but you can't enter.'
What is the difference between let and var?
The core difference is scope and hoisting. var is function-scoped and gets hoisted, while let is block-scoped and stays where you put it.
Think of var like a loud speaker in a room. Once you turn it on, everyone in the entire room (the function) can hear it, even if you're standing in a tiny corner (a loop or an if-block). But let is like a private whisper. It only exists inside the specific box or 'lunchbox' where it was created. If you define a let variable inside a for-loop, it doesn't leak out to the rest of your code.
Most tutorials get this wrong by just saying 'one is old, one is new'. The real pain is when var causes bugs because it lets you use a variable before it's even declared.
Check this out:
function scopeTest() {
if (true) {
var loudSpeaker = 'I am everywhere!';
let privateWhisper = 'I am hidden';
}
console.log(loudSpeaker); // Works! 'I am everywhere!'
console.log(privateWhisper); // ReferenceError: privateWhisper is not defined
}
And then there's hoisting. With var, JavaScript moves the declaration to the top. It's like moving furniture into a new house before you even arrive. With let, you can't touch the variable until the code actually hits that line.
One big trap? Using var in loops with asynchronous code. You'll end up with the final value of the loop for every single iteration because they all share that one 'loud speaker'. Switch to let and each iteration gets its own fresh, isolated environment. It's the difference between a shared messy desk and giving every worker their own organized workstation.
What is the difference between microtasks and macrotasks in the Event Loop?
In JavaScript, the Event Loop handles asynchronous callbacks by dividing them into two queues:
- Microtask Queue: Promises (
.then,.catch,.finally),queueMicrotask(), andMutationObserver. These are executed immediately after the currently running script and before rendering or any macrotask. - Macrotask (Task) Queue:
setTimeout,setInterval,setImmediate, I/O events, and UI rendering.
What is the difference between == and === in JavaScript?
== checks value equality with type coercion—it converts types before comparing. === checks both value and type without conversion. '5' == 5 is true, but '5' === 5 is false. Using === is safer and avoids unexpected bugs.
What is type coercion in JavaScript?
Type coercion is JavaScript's automatic conversion of one data type to another during comparisons or operations. It can lead to surprising results and is one reason === is preferred over ==.
What is closure in JavaScript?
A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing. It's like a backpack—the inner function carries its environment with it wherever it goes.
Where are closures commonly used in real projects?
Closures are used in callbacks, event handlers, factory functions, and module patterns. For example, a counter function that keeps its own private count without exposing it globally.
What is event delegation in JavaScript?
Event delegation attaches a single event listener to a parent element to handle events from its children. Instead of adding listeners to every button, you listen once on the container. It's like having one receptionist for an entire office floor instead of one per room.
What is event bubbling and how does it relate to delegation?
Event bubbling means an event triggered on a child element travels up to its parents. Delegation works because of bubbling—the parent catches events that bubble up from children. You can stop bubbling using event.stopPropagation() when needed.
What is a primary key in MySQL and why is it important?
A primary key uniquely identifies each row in a table. It’s like an Aadhaar number for database records—no two rows can have the same one. It ensures data integrity and helps retrieve records quickly.
What is an index in MySQL and how does it improve performance?
An index speeds up data retrieval by creating a lookup structure. Just like a book index helps you jump to a page instead of reading the whole book, database indexes allow faster searches but slightly slow down inserts and updates.
What is a transaction in MySQL?
A transaction groups multiple database operations into a single unit of work. Either all operations succeed or all fail. It’s like a bank transfer—money must be debited and credited together or not at all.
What are ACID properties?
ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties ensure transactions are reliable and data remains correct even during failures.
What is database normalization?
Normalization organizes data to reduce duplication and improve consistency. It’s like storing customer details once instead of repeating them in every order.
What is the difference between SQL JOIN types (INNER, LEFT, RIGHT, FULL)?
JOIN combines rows from two tables based on a related column. INNER JOIN returns only matching rows. LEFT JOIN returns all rows from the left table and matching ones from the right. RIGHT JOIN is the opposite. FULL JOIN returns everything. Think of it like two guest lists—INNER is people on both lists, LEFT is everyone from list A plus matches from list B.
When would you use a LEFT JOIN over an INNER JOIN?
Use LEFT JOIN when you want all records from the primary table even if there's no match in the related table. For example, getting all customers even if they haven't placed an order yet.
What is the difference between JOIN and UNION in MySQL?
JOIN combines columns from multiple tables horizontally. UNION stacks rows from multiple queries vertically. JOIN is for related data, UNION is for merging similar result sets.
What is the event loop in Node.js and why is it important?
The event loop allows Node.js to handle multiple operations without blocking the main thread. Imagine a waiter taking multiple orders instead of waiting at one table. Node can handle thousands of requests efficiently because the event loop manages async tasks like I/O operations.
What is Express.js and how is it used in Node.js?
Express.js is a lightweight framework on top of Node.js used to build web servers and REST APIs. Think of Node.js as raw ingredients and Express as a ready-made kitchen setup that lets you cook faster and cleaner.
What is middleware in Express.js?
Middleware is a function that executes between the request and response cycle in Express.js. It can modify requests, responses, or stop the request entirely. It’s like airport security—every request must pass through checks before reaching its destination.
What is error-handling middleware in Express?
Error-handling middleware catches errors centrally and sends consistent error responses. It prevents the app from crashing and improves debugging and user experience.
What is the purpose of package.json in Node.js?
package.json manages project metadata, dependencies, and scripts. It’s like a recipe card—anyone can recreate the same dish by following it.
Why is package-lock.json important?
package-lock.json locks exact dependency versions to ensure the same behavior across environments. It prevents the 'works on my machine' problem.
When would you choose NoSQL over SQL?
Choose NoSQL when data is unstructured or changes frequently, you need horizontal scaling, or you're building real-time apps like chat or analytics. MongoDB, Redis, and Cassandra are common choices.
What are SOLID principles and why do they matter?
SOLID is a set of five design principles that make code more maintainable, scalable, and testable. Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. Following them prevents code from becoming a tangled mess as projects grow.
What is the Single Responsibility Principle?
A class should have only one reason to change—meaning it should only do one thing. A class that handles both user authentication and sending emails violates SRP and becomes hard to maintain.
What is the Virtual DOM in React and why does it exist?
The Virtual DOM is an in-memory representation of the real DOM. React updates the Virtual DOM first, calculates the minimal changes needed, and then updates the real DOM. It's like drafting a document before printing—fewer costly re-renders, better performance.
What is reconciliation in React?
Reconciliation is the process React uses to compare the previous and new Virtual DOM trees (diffing) to figure out the minimum set of DOM changes required. It makes updates fast and efficient.
What are React Hooks and why were they introduced?
Hooks let functional components use state and lifecycle features that were previously only available in class components. They were introduced to simplify component logic and make code reusable. useState, useEffect, and useContext are the most common ones.
What is the useEffect hook used for?
useEffect handles side effects in functional components—like fetching data, subscribing to events, or updating the DOM. It replaces lifecycle methods like componentDidMount and componentDidUpdate from class components.
What are the rules of hooks in React?
Hooks must only be called at the top level of a function—not inside loops, conditions, or nested functions. They must only be called from React functional components or custom hooks, not regular JavaScript functions.
What is JWT (JSON Web Token) and how does it work?
JWT is a compact, self-contained token used for authentication and authorization. It contains encoded user data and is signed to prevent tampering. It's like a stamped ID badge—the guard checks the stamp without calling HR every time.
What are the three parts of a JWT?
A JWT has three parts: Header (algorithm info), Payload (user claims/data), and Signature (verification). They are base64-encoded and separated by dots.
What is the difference between authentication and authorization?
Authentication verifies who you are (logging in). Authorization determines what you're allowed to do (access control). A hotel key card authenticates you; the floor it opens authorizes your access.
What is Dependency Inversion in SOLID?
Dependency Inversion means depending on abstractions rather than concrete implementations. It’s like using a universal charging cable instead of device-specific chargers.
Explain the Cache-Aside pattern vs Write-Through caching.
Cache-Aside (Lazy Loading): The application first queries the cache. On a cache miss, it reads from the primary database, writes the entry into the cache, and returns it. Best for read-heavy workloads where data changes infrequently.
Write-Through: The application writes data to the cache, and the cache synchronously updates the database. Ensures data is always fresh in cache at the cost of higher write latency.