Skip to content

Web Development Interview Questions for 2 Years Experience

40 questions with answers for candidates with 2 years of experience — 5 easy, 34 medium, 1 hard.

What interviewers expect: 2 years experience

At two years, you are expected to work independently on modules. Interviews include JavaScript internals like the event loop, Laravel or MVC structure, database design, indexes and security basics like XSS and CSRF. Scenario questions test how you would handle slow pages, login issues or broken layouts in production.

This set is weighted towards PHP Programming (7), DOM and Browser Events (6), Hosting and Deployment (5), Web Security (5).

MVC and Laravel Database design Web security basics Performance fixes
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between preventDefault and stopPropagation?

Save to ▾
Show answer
preventDefault stops the browser's default action for the event, such as a form submitting and reloading the page or a link navigating. stopPropagation stops the event from bubbling further to parent elements, but the default action still happens. They solve different problems and are sometimes used together. Overusing stopPropagation can break delegated listeners and analytics scripts that listen at the document level.
02

What are the differences between Apache and Nginx?

Save to ▾
Show answer
Apache uses a process or thread based model and supports per-directory .htaccess files, which is convenient on shared hosting. Nginx uses an event-driven model that handles many concurrent connections with low memory, making it excellent for static files and as a reverse proxy. Nginx runs PHP through PHP-FPM and has no .htaccess, so rules go in central config. Many setups put Nginx in front of Apache or application servers.
03

What is event delegation and why is it useful?

Save to ▾
Show answer
Event delegation attaches one listener to a common parent instead of many listeners on child elements, then uses event.target.closest() to find which child was clicked. Because of bubbling, it works even for children added later. For example, one listener on a ul can handle delete buttons for hundreds of todo items. It saves memory and avoids re-binding listeners after dynamic updates.
04

Database credentials were accidentally pushed to a public GitHub repository. What now?

Save to ▾
Show answer
Deleting the commit is not enough, because bots scan GitHub within minutes. I would immediately rotate the password and any other exposed keys, check database logs for suspicious access, and then purge the secret from history using git filter-repo. Going forward, secrets belong in environment variables or a secrets manager, .env files go in .gitignore, and secret-scanning tools run in CI.
05

What is the difference between block-level and inline elements?

Save to ▾
Show answer
Block-level elements such as div, p, h1 and section start on a new line and take the full available width by default. Inline elements such as span, a, strong and img sit inside a line of text and only take as much width as their content. Inline elements ignore vertical width and height settings, which is why developers often switch them to inline-block or block when they need sizing.
06

Build a simple PHP endpoint that returns JSON.

Save to ▾
Show answer
Set the header, encode the data and use proper status codes: header('Content-Type: application/json'); $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); if (!$id) { http_response_code(400); echo json_encode(['error' => 'Invalid id']); exit; } $stmt = $pdo->prepare('SELECT id, name, price FROM courses WHERE id = ?'); $stmt->execute([$id]); $course = $stmt->fetch(PDO::FETCH_ASSOC); http_response_code($course ? 200 : 404); echo json_encode($course ?: ['error' => 'Not found']);
07

What is the difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy, made with spread syntax or Object.assign, copies only top-level properties, so nested objects are still shared references. Changing copy.address.city also changes the original. A deep copy duplicates every nested level. Modern browsers and Node provide structuredClone(obj), which handles dates, maps and circular references. JSON.parse(JSON.stringify(obj)) also works but drops functions, undefined and converts dates to strings.
08

Tell me about a time you disagreed with a designer about a layout.

Save to ▾
Show answer
Situation: a designer wanted a five-column pricing table on mobile. Task: I had to deliver the design while keeping it usable on small screens. Action: I built a quick prototype on a real phone, showed that text became unreadable, and proposed a swipeable card version that kept the same visual style. Result: the designer agreed, we updated the Figma file together, and mobile conversions on that page improved after launch.
09

Implement dark mode using CSS custom properties.

Save to ▾
Show answer
Define colour tokens and override them for dark preference: :root { --bg: #ffffff; --text: #1f2937; } @media (prefers-color-scheme: dark) { :root { --bg: #111827; --text: #f3f4f6; } } [data-theme='dark'] { --bg: #111827; --text: #f3f4f6; } body { background: var(--bg); color: var(--text); } The media query follows the system setting, and the data-theme attribute lets a toggle button override it with JavaScript.
10

Create students, courses and enrollments tables with proper keys.

Save to ▾
Show answer
A many-to-many relationship needs a junction table: CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(150) NOT NULL UNIQUE ); CREATE TABLE courses ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(150) NOT NULL ); CREATE TABLE enrollments ( student_id INT, course_id INT, enrolled_on DATE NOT NULL, PRIMARY KEY (student_id, course_id), FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE, FOREIGN KEY (course_id) REFERENCES courses(id) );
11

A comment section displays user input using innerHTML. What is the risk and fix?

Save to ▾
Show answer
It allows stored cross-site scripting: a user can post <img src=x onerror=...> and the script runs for every visitor, stealing sessions or defacing the page. I would switch to textContent or createElement for rendering, escape output on the server, and if rich text is needed, sanitise with a library like DOMPurify. A strict Content Security Policy adds another layer by blocking inline scripts.
12

Tell me about a time a website went down and how you handled it.

Save to ▾
Show answer
Situation: our e-commerce site went down at 11 PM during a sale. Task: as the on-call developer, I had to restore it fast. Action: I checked logs, found PHP-FPM workers exhausted by a slow query, restarted the service, added an index to fix the query, and kept the team updated every 15 minutes. Result: the site was back in 20 minutes, and I wrote a postmortem with monitoring alerts to catch it earlier.
13

What are CSS custom properties and how are they different from Sass variables?

Save to ▾
Show answer
Custom properties like --brand: #2563eb are defined in CSS and read with var(--brand). They cascade, can be changed per element or media query, and can be updated at runtime with JavaScript, which makes themes and dark mode easy. Sass variables are replaced at compile time and do not exist in the browser. Many teams use both: Sass for build-time logic and custom properties for runtime theming.
14

How did string and number comparison with == change in PHP 8?

Save to ▾
Show answer
Before PHP 8, comparing a number with a non-numeric string converted the string to a number, so 0 == 'abc' was true, which caused security bugs. Since PHP 8, if the string is not numeric, the number is converted to a string and compared as strings, so 0 == 'abc' is now false. Using === is still recommended because it checks type and value without any conversion.
15

An API is being called twice when the page loads. How do you debug it?

Save to ▾
Show answer
I would open the Network tab and check the Initiator column to see which code triggered each request. Common causes are the script being included twice, an event listener attached twice, a function called on both DOMContentLoaded and load, or a framework's development mode running effects twice. I would add a breakpoint or console.trace inside the fetch function, fix the root cause, and add a guard flag only if truly needed.
16

Explain closures with an example.

Save to ▾
Show answer
A closure is a function that remembers variables from the scope where it was created, even after that outer function has finished. For example, function counter() { let count = 0; return () => ++count; } returns a function that keeps its own private count. Closures are used for data privacy, function factories, debounce helpers and event handlers. Their trade-off is that captured variables stay in memory as long as the function exists.
17

What is CSRF and how do you prevent it?

Save to ▾
Show answer
Cross-site request forgery tricks a logged-in user's browser into sending an unwanted request, such as changing their email, because cookies are attached automatically. Prevention includes a unique CSRF token in every state-changing form that the server verifies, SameSite=Lax or Strict cookies, and checking the Origin header. GET requests should never change data. Frameworks like Laravel add CSRF tokens to forms by default.
18

Why is the meta viewport tag needed for mobile pages?

Save to ▾
Show answer
Without a viewport meta tag, mobile browsers render the page at a virtual width of around 980 pixels and then zoom out, so text looks tiny. Adding <meta name='viewport' content='width=device-width, initial-scale=1'> tells the browser to use the real device width, which makes media queries work as expected. Avoid disabling user zoom with maximum-scale=1 because it hurts accessibility for users with low vision.
19

Deploy a PHP project to a VPS using Git and SSH.

Save to ▾
Show answer
A simple scripted deployment: ssh deploy@server.example.com << 'EOF' cd /var/www/app git pull origin main composer install --no-dev --optimize-autoloader php artisan migrate --force php artisan config:cache sudo systemctl reload php8.3-fpm EOF Use an SSH key, not a password, and a non-root deploy user. Reloading PHP-FPM clears OPcache so new code is served. For safer releases, deploy into a new folder and switch a symlink.
20

Tell me about a time you found a security issue in someone else's code.

Save to ▾
Show answer
Situation: during a code review, I noticed a teammate built a search query by concatenating user input. Task: I had to flag it without making them feel blamed. Action: I messaged them privately, showed a harmless injection example on staging, and suggested a prepared statement fix with a short snippet. Result: they fixed it before release, and we added a SQL injection check to our review checklist.
21

A client insists on a major deployment on Friday evening. How do you respond?

Save to ▾
Show answer
Situation: a client wanted a big redesign live before a weekend campaign. Task: I had to respect their goal but reduce risk. Action: I explained that weekend issues would have fewer people to fix them, proposed deploying Thursday morning on staging-tested code, and arranged a rollback plan and someone on call. Result: the client agreed, we deployed Thursday, fixed two small issues the same day, and the campaign ran smoothly.
22

What are data-* attributes and when do you use them?

Save to ▾
Show answer
Custom data attributes such as data-product-id or data-price let you store extra information on an element without misusing class or id. JavaScript reads them through element.dataset, for example button.dataset.productId, and CSS can target them with attribute selectors. They are ideal for passing small values from server-rendered HTML to scripts, but sensitive data should never be stored there because anyone can read the page source.
23

What is the difference between an abstract class and an interface in PHP?

Save to ▾
Show answer
An interface defines only method signatures and constants, and a class can implement many interfaces. An abstract class can contain properties, constructors and implemented methods along with abstract ones, but a class can extend only one. Use an interface to define a contract like PaymentGateway, and an abstract class to share common code among closely related classes, such as a base Controller.
24

What is MVC and how does Laravel follow it?

Save to ▾
Show answer
MVC separates an application into Models for data and business rules, Views for presentation, and Controllers that handle requests and connect the two. In Laravel, routes send a request to a controller, the controller uses Eloquent models to query the database, and returns a Blade view or JSON. This separation makes code testable and lets frontend and backend developers work on different layers without conflicts.
25

What is CORS and why does the browser block some API calls?

Save to ▾
Show answer
The same-origin policy stops scripts on one origin from reading responses from another origin. CORS is how a server opts in: it returns headers like Access-Control-Allow-Origin naming allowed origins. For non-simple requests, such as JSON with custom headers, the browser first sends an OPTIONS preflight. CORS is enforced only by browsers, so it is not a security control for the server itself, and Allow-Origin * should never be combined with credentials.
26

Validate and sanitise different types of input in PHP.

Save to ▾
Show answer
Use filter functions and allow-lists: $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); $age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, ['options' => ['min_range' => 18, 'max_range' => 60]]); $sort = in_array($_GET['sort'] ?? '', ['name', 'price'], true) ? $_GET['sort'] : 'name'; if ($email === false || $age === false) { $errors[] = 'Please enter a valid email and age.'; } Allow-lists are essential for values like column names that cannot be bound as prepared statement parameters.
27

Users click the Pay button twice and get charged twice. How do you prevent it?

Save to ▾
Show answer
On the front end, I would disable the button and show a loading state as soon as the first click is handled, and re-enable it only on error. But the real fix must be on the server: generate an idempotency key or order id per checkout, and reject or ignore a second request with the same key. Payment gateways support idempotent requests for exactly this reason.
28

Open and close an accessible modal using the native dialog element.

Save to ▾
Show answer
The dialog element handles focus and the Escape key for you: <button id='open'>Enquire now</button> <dialog id='enquiry'> <form method='dialog'> <p>Thank you for your interest.</p> <button>Close</button> </form> </dialog> <script> const dlg = document.getElementById('enquiry'); document.getElementById('open').addEventListener('click', () => dlg.showModal()); </script> showModal places it in the top layer with a backdrop, and form method='dialog' closes it without a request.
29

Write an accessible login form with proper labels.

Save to ▾
Show answer
Every input needs a label linked through for and id, the right input type and autocomplete hints: <form action='/login' method='post'> <label for='email'>Email</label> <input id='email' name='email' type='email' autocomplete='email' required> <label for='pwd'>Password</label> <input id='pwd' name='password' type='password' autocomplete='current-password' required minlength='8'> <button type='submit'>Log in</button> </form> Clicking a label focuses its input and screen readers read the label aloud.
30

Users lose a long form's data when they accidentally refresh. How do you solve it?

Save to ▾
Show answer
I would autosave the form into sessionStorage or localStorage on input with a small debounce, then restore values on page load and clear them after successful submission. A beforeunload warning can ask users to confirm leaving when there are unsaved changes. Sensitive fields like passwords or card details must never be saved. For multi-step forms, saving drafts on the server is more reliable.
31

What is the difference between Promises and async/await?

Save to ▾
Show answer
A Promise represents a value that will be available later, handled with then and catch chains. async/await is syntax built on promises: an async function always returns a promise, and await pauses that function until the promise settles, making code read top to bottom. Errors are handled with try and catch. For parallel work you still use Promise.all, because awaiting calls one by one runs them sequentially.
32

What are PHP superglobals?

Save to ▾
Show answer
Superglobals are built-in arrays available in every scope without the global keyword. Common ones are $_GET and $_POST for request data, $_REQUEST combining them, $_SESSION, $_COOKIE, $_FILES for uploads, $_SERVER for headers and paths, and $_ENV for environment variables. All user-supplied superglobals must be treated as untrusted input and validated, for example using filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL).
33

Schedule a nightly database backup with cron.

Save to ▾
Show answer
Edit the crontab with crontab -e and add: 30 2 * * * mysqldump --single-transaction -u backup school | gzip > /backups/school_$(date +\%F).sql.gz 0 3 * * * find /backups -name '*.sql.gz' -mtime +14 -delete The first line runs at 2:30 AM daily; the second removes backups older than 14 days. Keep credentials in ~/.my.cnf with restricted permissions instead of the command, escape % in crontab, and copy backups to off-server storage.
34

Write a debounce function and explain where it is used.

Save to ▾
Show answer
Debounce delays a function until calls stop for a given time: function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const onSearch = debounce((e) => fetchResults(e.target.value), 300); input.addEventListener('input', onSearch); It is used for search boxes, window resize and autosave, so the API is called once after the user pauses typing.
35

What is the difference between sessions and cookies in PHP?

Save to ▾
Show answer
A cookie stores data in the browser and is sent with every request, so users can see and edit it. A session stores data on the server and keeps only a session id in a cookie, usually PHPSESSID. Use $_SESSION for login state and cart data, after calling session_start(). Use cookies only for non-sensitive preferences, and mark session cookies HttpOnly, Secure and SameSite.
36

What are transactions and ACID properties?

Save to ▾
Show answer
A transaction groups several SQL statements so they succeed or fail together. ACID means Atomicity, all or nothing; Consistency, rules and constraints stay valid; Isolation, concurrent transactions do not see each other's partial changes; and Durability, committed data survives crashes. For example, transferring wallet balance debits one row and credits another inside START TRANSACTION and COMMIT, with ROLLBACK if anything fails.
37

Your page shows a horizontal scrollbar on mobile. How do you find and fix the cause?

Save to ▾
Show answer
Horizontal scroll means some element is wider than the viewport. I would open Chrome DevTools device mode and use a temporary rule like * { outline: 1px solid red } to spot the culprit. Common causes are fixed pixel widths, images without max-width: 100%, long unbroken URLs, and 100vw combined with padding. Fixes include max-width, overflow-wrap: anywhere and box-sizing: border-box. I avoid hiding it with overflow-x: hidden without fixing the root cause.
38

Show monthly revenue for the current year from an orders table.

Save to ▾
Show answer
Group by month and sum the amounts: SELECT DATE_FORMAT(created_at, '%Y-%m') AS month, COUNT(*) AS orders, SUM(amount) AS revenue FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01' AND status = 'paid' GROUP BY month ORDER BY month; Using a date range instead of YEAR(created_at) = 2026 lets MySQL use an index on created_at.
39

Users get logged out immediately after login when redirected. What could be wrong?

Save to ▾
Show answer
Likely causes are session_start() missing on the next page, output sent before session_start so headers fail, or the session cookie being dropped. Cookie issues include a Secure flag on an HTTP site, a domain mismatch between www and non-www, or SameSite settings during cross-site redirects. I would check the Set-Cookie header in DevTools, verify session.save_path is writable, and redirect to a single canonical domain.
40

What is margin collapsing?

Save to ▾
Show answer
When vertical margins of adjacent block elements touch, they merge into a single margin equal to the larger one instead of adding up. It also happens between a parent and its first or last child when no padding, border or block formatting context separates them. Margins do not collapse in flex or grid containers. Developers often avoid surprises by using padding, gap or margin in one direction only.

Frequently asked questions

What is asked in Web Development interviews for 2 years of experience?

At two years, you are expected to work independently on modules. Interviews include JavaScript internals like the event loop, Laravel or MVC structure, database design, indexes and security basics like XSS and CSRF. Scenario questions test how you would handle slow pages, login issues or broken layouts in production.

How many questions should I practise before a Web Development interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 2 years of experience?

Focus first on MVC and Laravel, Database design, Web security basics, Performance fixes.