Fullstack Flashcards
(30 cards)
What is the difference between block
and inline-block
in CSS?
block
elements (e.g., <div>
) take full width and start on a new line; inline-block
allows inline flow with block properties like width/height. Example: display: inline-block;
.
How do you center a div both horizontally and vertically using CSS?
```css
div {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
/* Explanation: Flexbox aligns content in both axes (O(1) layout). */
~~~
What is event delegation in JavaScript?
Event delegation uses event bubbling to handle events on a parent element for its children. Example: Add click listener to <ul>
to handle <li>
clicks (reduces listeners).
How do you debounce a function in JavaScript for frontend performance?
```javascript
function debounce(func, wait) {
let timeout;
return (…args) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(…args), wait);
};
}
// Example: debounce(() => search(), 300) limits rapid calls (O(1)).
~~~
What is a React component, and how do you create one?
A React component is a reusable UI piece returning JSX. Example: function MyComponent() { return <div>Hello</div>; }
or class MyComponent extends React.Component { render() { return <div>Hello</div>; } }
.
Explain the useEffect
hook in React.
useEffect
handles side effects (e.g., API calls) after render. Example: useEffect(() => { fetchData(); }, [id]);
runs when id
changes.
How do you handle forms in React with multiple inputs?
```javascript
function Form() {
const [form, setForm] = useState({ name: ‘’, email: ‘’ });
const handleChange = (e) => setForm({ …form, [e.target.name]: e.target.value });
return (
<form>
<input name=’name’ value={form.name} onChange={handleChange} />
<input name=’email’ value={form.email} onChange={handleChange} />
</form>
);
}
// Explanation: Uses a single state object for multiple inputs (O(1) updates).
~~~
What is React.memo
, and when is it used?
React.memo
memoizes a component to prevent re-renders unless props change. Example: const Memoized = React.memo(MyComponent);
, used for performance optimization.
How do you implement lazy loading in React?
```javascript
const LazyComponent = React.lazy(() => import(‘./Component’));
function App() {
return (
<Suspense fallback={<div>Loading…</div>}>
<LazyComponent></LazyComponent>
</Suspense>
);
}
// Explanation: React.lazy
and Suspense
defer component loading (O(1) setup).
~~~
What is the purpose of ARIA attributes in HTML?
ARIA attributes enhance accessibility. Example: role='button' aria-label='Close'
describes a custom button for screen readers.
What is a REST API, and what are its key principles?
A REST API uses HTTP methods (GET, POST, PUT, DELETE) for stateless, resource-based communication. Principles: statelessness, client-server, uniform interface.
How does Node.js handle asynchronous operations?
Node.js uses an event loop for non-blocking I/O, processing callbacks, Promises, or async/await. Example: fs.promises.readFile('file.txt')
reads files asynchronously.
Write a Node.js Express route to handle a GET request.
```javascript
const express = require(‘express’);
const app = express();
app.get(‘/users/:id’, (req, res) => {
res.json({ id: req.params.id, name: ‘User’ });
});
// Example: GET /users/1 → { id: ‘1’, name: ‘User’ }
// Explanation: Returns JSON for a user by ID (O(1)).
~~~
What is JWT, and how is it used in a full-stack app?
JWT (JSON Web Token) is a token for secure authentication. Frontend sends Authorization: Bearer <token>
; backend verifies it. Example: jwt.verify(token, 'secret')
.
How do you implement JWT authentication in Node.js?
```javascript
const jwt = require(‘jsonwebtoken’);
function authenticateToken(req, res, next) {
const token = req.headers[‘authorization’]?.split(‘ ‘)[1];
if (!token) return res.status(401).send(‘Unauthorized’);
jwt.verify(token, ‘secret’, (err, user) => {
if (err) return res.status(403).send(‘Forbidden’);
req.user = user;
next();
});
}
// Explanation: Verifies JWT, attaches user to request (O(1)).
~~~
What is the difference between SQL and NoSQL databases?
SQL databases (e.g., MySQL) are relational, use tables, and support SQL; NoSQL databases (e.g., MongoDB) are non-relational, flexible for unstructured data.
Write a SQL query to join two tables for employee and department data.
```sql
SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.id;
– Explanation: Matches employees to departments via department_id (O(n)).
~~~
How do you optimize a slow SQL query?
Use EXPLAIN
to analyze, add indexes on filtered/joined columns, reduce selected columns, and replace subqueries with joins.
What is caching, and how is it used in a full-stack app?
Caching stores data (e.g., in Redis) to reduce database load. Example: Cache API responses in backend, serve from cache in frontend to improve speed (O(1) lookup).
How does the fs
module in Node.js handle file operations?
```javascript
const fs = require(‘fs’).promises;
async function readFile() {
const data = await fs.readFile(‘file.txt’, ‘utf8’);
return data;
}
// Explanation: Reads file asynchronously, returning content (O(n)).
~~~
What is CORS, and how do you handle it in a full-stack app?
CORS controls cross-origin requests. In Express: app.use(cors({ origin: 'http://frontend.com' }));
allows frontend domain to access backend API.
How do you handle errors in a Node.js backend?
```javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: ‘Internal Server Error’ });
});
// Explanation: Global error middleware catches unhandled errors, returns 500 response.
~~~
What is the difference between localStorage
and sessionStorage
in the browser?
localStorage
persists until cleared; sessionStorage
lasts until tab closes. Example: localStorage.setItem('key', 'value');
stores persistently.
How do you fetch data from an API in React?
```javascript
function DataComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetch(‘/api/data’)
.then(res => res.json())
.then(setData);
}, []);
return <div>{data ? data.name : ‘Loading…’}</div>;
}
// Explanation: Fetches data on mount, updates state (O(1) render).
~~~