Skip to content

Web Development Interview Questions for Freshers

40 questions with answers for candidates with Freshers — 25 easy, 14 medium, 1 hard.

What interviewers expect: freshers

Freshers are tested on HTML, CSS and JavaScript fundamentals, simple PHP and SQL queries, and their projects. Expect questions on the box model, Flexbox, closures, event delegation, joins and form handling, plus a small coding task such as building a responsive card or a todo list. Interviewers check how clearly you explain your own project code.

This set is weighted towards DOM and Browser Events (8), CSS Layout and Responsive Design (7), HTML Fundamentals (7), JavaScript Core (5).

HTML and CSS basics JavaScript fundamentals Basic PHP and SQL Portfolio projects
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

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

Your code throws 'Unexpected token < in JSON' after an API call. What does it mean?

Save to ▾
Show answer
It means response.json() received HTML instead of JSON, usually an error page, a login redirect, or a 404 page from the server. I would check the response status and body in the Network tab, verify the endpoint URL and method, and confirm the server sets Content-Type: application/json. In code I would check response.ok before parsing so users see a clear error instead of a crash.
03

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

A client wants better Google rankings. What HTML-level changes would you make?

Save to ▾
Show answer
I would give every page a unique title and meta description, use exactly one clear h1 with a logical h2 and h3 structure, and add descriptive alt text. I would add canonical tags to avoid duplicate content, structured data such as JSON-LD for courses or FAQs, and internal links with meaningful anchor text. I would also improve Core Web Vitals, since page speed affects ranking.
05

Why do you want to work as a web developer?

Save to ▾
Show answer
I enjoy building things people use directly. During college, I made a website for a local library, and seeing members search books online gave me real satisfaction. Web development lets me combine design with logic, from HTML and CSS to PHP and MySQL, and see results immediately. I want to grow in a team that ships real products and eventually take ownership of complete features end to end.
06

Tell me about a website you built from scratch.

Save to ▾
Show answer
Situation: during my final year, a local coaching institute needed a website. Task: I had to build a responsive site with course pages and an enquiry form in three weeks. Action: I designed the layout in Figma, built it with semantic HTML, CSS Grid and JavaScript, stored enquiries in MySQL through PHP and deployed it on shared hosting. Result: it scored above 90 in Lighthouse and brought enquiries within the first month.
07

Uploaded images overflow their containers and break the layout. What is the fix?

Save to ▾
Show answer
Images keep their natural size by default, so a 2000 pixel photo will overflow a 350 pixel card. A global rule img { max-width: 100%; height: auto; display: block; } makes them shrink to fit while keeping the aspect ratio. For fixed-size thumbnails I would add width, height and object-fit: cover so different photo shapes crop neatly without stretching.
08

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

What is PHP and how does a PHP page get processed?

Save to ▾
Show answer
PHP is a server-side scripting language widely used for websites, WordPress, Laravel apps and APIs. When a browser requests a .php file, the web server such as Apache or Nginx passes it to the PHP interpreter, usually through PHP-FPM. PHP runs the code, talks to databases if needed, and sends back plain HTML or JSON. The browser never sees the PHP source, only the generated output.
10

When should you use CHAR, VARCHAR and TEXT?

Save to ▾
Show answer
CHAR(n) stores a fixed length and pads shorter values, which suits fixed codes like a 6-digit PIN code or two-letter state code. VARCHAR(n) stores variable length up to n characters with a small length prefix, ideal for names and emails. TEXT is for long content like blog bodies but cannot have a default value and is indexed only by prefix. Using right-sized types saves memory and improves index efficiency.
11

Compare shared hosting, VPS and cloud hosting.

Save to ▾
Show answer
Shared hosting puts many sites on one server with a control panel like cPanel; it is cheap and easy but offers limited resources and control. A VPS gives you a virtual machine with root access, dedicated RAM and CPU, so you install and secure the stack yourself. Cloud platforms like AWS, Azure and Google Cloud add auto-scaling, managed databases and pay-per-use pricing, suited to growing applications.
12

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

Create a responsive card grid that needs no media queries.

Save to ▾
Show answer
auto-fit with minmax lets the grid decide how many columns fit: .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; } Each card is at least 250 pixels wide and the extra space is shared equally. On a phone it shows one column, on a tablet two and on a desktop three or four, all from three lines of CSS.
14

Compare localStorage, sessionStorage and cookies.

Save to ▾
Show answer
localStorage stores about 5 MB per origin and persists until cleared. sessionStorage has similar size but is cleared when the tab closes and is separate per tab. Cookies are small, around 4 KB, are sent to the server with every request, and can be HttpOnly, Secure and SameSite. Use cookies for session identifiers, and storage for UI preferences. Never store tokens or passwords in localStorage, since any XSS can read it.
15

How does CSS specificity work?

Save to ▾
Show answer
Specificity decides which rule wins when several match the same element. It is calculated as a score: inline styles highest, then id selectors, then classes, attributes and pseudo-classes, then element and pseudo-element selectors. For example, #menu a beats .nav a. When specificity is equal, the rule written later wins. !important overrides normal rules, but overusing it creates maintenance problems, so keeping selectors flat with classes is preferred.
16

How would you explain a technical problem to a non-technical client?

Save to ▾
Show answer
Situation: a client asked why their site was slow on mobile. Task: I needed approval to optimise images, which meant extra work. Action: I avoided jargon, showed a side-by-side video of load times, and compared large images to sending a heavy parcel by post. Result: the client approved the work, load time dropped from 7 to 2.5 seconds, and they trusted my later suggestions more.
17

An accessibility audit gives your site a low score. What would you fix first?

Save to ▾
Show answer
I would start with issues that block users completely: missing alt text on meaningful images, form inputs without labels, poor colour contrast, and controls that cannot be reached by keyboard. Then I would fix heading order, add a skip link, use semantic landmarks and make focus outlines visible. I would test with Lighthouse or axe, then manually with Tab key navigation and a screen reader like NVDA.
18

Escape user data correctly when printing it in PHP templates.

Save to ▾
Show answer
Escape at output time for the right context: function e(string $value): string { return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } echo '<p>' . e($comment) . '</p>'; echo "<input value='" . e($name) . "'>"; $url = urlencode($search); echo '<a href="/search?q=' . $url . '">Search</a>'; ENT_QUOTES escapes both quote types so attributes are safe. JavaScript and URL contexts need their own encoding; Blade's double braces do this automatically.
19

How do you test a website for cross-browser compatibility?

Save to ▾
Show answer
I check feature support on Can I Use before using new CSS, and use Autoprefixer through the build for vendor prefixes. I test on Chrome, Firefox, Safari and Edge, plus real Android and iPhone devices because Safari on iOS behaves differently. Cloud testing platforms help when devices are missing. I use @supports for progressive enhancement, so older browsers still get a working, simpler layout.
20

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

What is the difference between pseudo-classes and pseudo-elements?

Save to ▾
Show answer
A pseudo-class selects an element in a particular state, such as :hover, :focus, :nth-child(2) or :checked, and uses a single colon. A pseudo-element styles a specific part of an element or inserts generated content, such as ::before, ::after, ::first-line or ::placeholder, and uses a double colon. For example, a::after can add an arrow icon after links without extra HTML.
22

Create a dark mode toggle that remembers the user's choice.

Save to ▾
Show answer
Store the choice in localStorage and apply it on load: const root = document.documentElement; const saved = localStorage.getItem('theme'); if (saved) root.dataset.theme = saved; toggle.addEventListener('click', () => { const next = root.dataset.theme === 'dark' ? 'light' : 'dark'; root.dataset.theme = next; localStorage.setItem('theme', next); toggle.setAttribute('aria-pressed', next === 'dark'); }); Running the first lines in a small inline script in the head avoids a flash of the wrong theme.
23

What is hoisting in JavaScript?

Save to ▾
Show answer
Hoisting means declarations are processed before code runs, so they behave as if moved to the top of their scope. Function declarations are hoisted completely and can be called before they appear. var variables are hoisted but set to undefined until assignment. let, const and class are hoisted too, but accessing them before declaration throws a ReferenceError because of the temporal dead zone.
24

Explain the difference between async and defer on a script tag.

Save to ▾
Show answer
Both download the script in parallel without blocking HTML parsing. An async script executes as soon as it finishes downloading, in no fixed order, so it suits independent scripts like analytics. A defer script waits until the HTML is fully parsed and runs in document order, so it suits application code that depends on the DOM or on other scripts. A plain script tag blocks parsing completely.
25

What is the difference between == and ===?

Save to ▾
Show answer
== compares values after type coercion, so 0 == '0' and null == undefined are both true, which can hide bugs. === is strict equality and returns true only when both type and value match, so 0 === '0' is false. Most style guides require === everywhere. One accepted exception is value == null, which conveniently checks for both null and undefined in one condition.
26

Use the PHP 8 match expression instead of a switch.

Save to ▾
Show answer
match returns a value, uses strict comparison and needs no break: $status = 'shipped'; $label = match ($status) { 'pending' => 'Order received', 'shipped', 'in_transit' => 'On the way', 'delivered' => 'Delivered', default => 'Unknown status', }; echo $label; Unlike switch, match throws an UnhandledMatchError if no arm matches and there is no default, which surfaces missing cases early.
27

A contact form is receiving hundreds of spam submissions daily. What do you do?

Save to ▾
Show answer
I would layer defences rather than rely on one trick. On the front end, add a hidden honeypot field that bots fill and humans do not, and add an invisible CAPTCHA such as reCAPTCHA v3 or Turnstile. On the server, validate every field, apply rate limiting per IP, reject submissions that arrive too fast after page load, and log patterns. Real protection must be server side because bots skip JavaScript.
28

Write a query to find the second highest salary.

Save to ▾
Show answer
Two common approaches: SELECT MAX(salary) AS second_highest FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1; The first returns NULL when there is no second value. With MySQL 8 you can also use DENSE_RANK() OVER (ORDER BY salary DESC) and filter rank = 2, which generalises to the Nth highest.
29

What is the difference between var, let and const?

Save to ▾
Show answer
var is function-scoped, is hoisted and initialised as undefined, and can be redeclared, which causes bugs in loops and blocks. let and const are block-scoped and sit in the temporal dead zone until their declaration line runs. let allows reassignment, while const does not, although objects declared with const can still have their properties changed. Modern code uses const by default and let only when the value must change.
30

Time to first byte is over 2 seconds even for simple pages. What do you check?

Save to ▾
Show answer
High TTFB points to the server, not the browser. I would check if OPcache is enabled, profile slow database queries, look for blocking external API calls during page generation, and check whether the server is low on CPU or memory. Fixes include full-page caching for anonymous users, object caching with Redis, upgrading PHP, choosing a server region close to Indian users, and putting a CDN in front.
31

What is the difference between UNION and UNION ALL?

Save to ▾
Show answer
Both combine the results of two SELECT queries with the same number and type of columns. UNION removes duplicate rows, which requires extra sorting or hashing work. UNION ALL keeps all rows, including duplicates, and is therefore faster. Use UNION ALL when you know results cannot overlap or duplicates are acceptable, for example combining this year's and last year's order tables.
32

What is the difference between DOMContentLoaded and the load event?

Save to ▾
Show answer
DOMContentLoaded fires when the HTML has been fully parsed and the DOM is built, without waiting for images, stylesheets or iframes. load fires on window only after every resource, including images, has finished loading. Most scripts that attach listeners should run on DOMContentLoaded, or simply use defer. load is useful when you need image dimensions or must start something after everything is ready.
33

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

Center a div horizontally and vertically using Flexbox and Grid.

Save to ▾
Show answer
Both methods work on the parent container: .parent-flex { display: flex; justify-content: center; align-items: center; min-height: 100vh; } .parent-grid { display: grid; place-items: center; min-height: 100vh; } place-items is shorthand for align-items and justify-items. Using min-height instead of height lets content grow without overflowing on small screens.
35

How do you handle pressure to skip security work to meet a deadline?

Save to ▾
Show answer
Situation: a manager wanted to launch a form without server-side validation to save a day. Task: I needed to protect the product without blocking the launch. Action: I explained the risk in business terms, data leaks and spam, and proposed shipping core validation and rate limiting now, with less critical hardening in the next sprint. Result: we launched on time with essential protections and completed the rest within a week.
36

Explain the common DNS record types.

Save to ▾
Show answer
An A record maps a domain to an IPv4 address and AAAA to IPv6. CNAME points one name to another, such as www to example.com, but cannot sit on the root domain. MX records route email to mail servers. TXT records hold verification and email security data like SPF, DKIM and DMARC. NS records name the authoritative nameservers. TTL controls how long resolvers cache each record.
37

What are truthy and falsy values?

Save to ▾
Show answer
In a boolean context, JavaScript converts values to true or false. The falsy values are false, 0, -0, 0n, empty string, null, undefined and NaN; everything else is truthy, including '0', empty arrays and empty objects. This matters in conditions: if (items.length) works, but if (count) fails when count is legitimately 0. The nullish coalescing operator ?? helps by only falling back for null or undefined.
38

What is the difference between echo and print in PHP?

Save to ▾
Show answer
Both output strings. echo is a language construct with no return value and can take multiple comma-separated arguments, like echo $a, $b. print also is a construct but takes only one argument and returns 1, so it can be used inside expressions. echo is marginally faster and far more common. For formatted output, printf or sprintf are used, for example printf('%.2f', $price).
39

How is querySelector different from getElementById and getElementsByClassName?

Save to ▾
Show answer
querySelector and querySelectorAll accept any CSS selector and return the first match or a static NodeList. getElementById accepts only an id and is slightly faster. getElementsByClassName returns a live HTMLCollection that updates automatically when the DOM changes, which can cause surprises inside loops. In practice querySelector is used for flexibility, and the speed difference rarely matters.
40

What is Composer and how does PSR-4 autoloading work?

Save to ▾
Show answer
Composer is PHP's dependency manager. composer.json lists packages, composer.lock pins exact versions, and the vendor folder holds installed code. PSR-4 maps a namespace prefix to a folder, for example App\ to src/, so App\Models\User loads from src/Models/User.php automatically after you require vendor/autoload.php. This removes manual require statements. composer.lock should be committed so every environment installs identical versions.

Frequently asked questions

What is asked in Web Development interviews for Freshers?

Freshers are tested on HTML, CSS and JavaScript fundamentals, simple PHP and SQL queries, and their projects. Expect questions on the box model, Flexbox, closures, event delegation, joins and form handling, plus a small coding task such as building a responsive card or a todo list. Interviewers check how clearly you explain your own project code.

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 Freshers?

Focus first on HTML and CSS basics, JavaScript fundamentals, Basic PHP and SQL, Portfolio projects.