In short
HTML marks up content and structure, CSS controls presentation and layout, and JavaScript adds behaviour by scripting the Document Object Model (DOM) in the browser. Together they are the three languages every browser runs natively (WebAssembly is the only other, and it is a compiled target rather than an authoring language), so every website, dashboard, admin panel and hybrid mobile app rests on them. Indian university syllabi examine them in "Web Technologies"/"Internet and Web Programming" papers and labs (AICTE model curriculum, CBCS), and GATE CS does not test them directly, though UGC-NET Computer Science and most PSU/IT written tests do. In placements at TCS, Infosys, Wipro, Accenture, Cognizant, Zoho, Freshworks and product startups, the front-end round almost always opens with the box model, flexbox, specificity, closures, this, hoisting, promises and the event loop.
Explained
HTML: structure and semantics
- HTML (HyperText Markup Language) is a markup language, not a programming language: tags describe meaning, the browser decides rendering. Current living standard is HTML5 maintained by WHATWG; W3C recommendations are now aligned to it.
- Minimum valid document:
<!DOCTYPE html>(triggers standards mode, not quirks mode),<html lang="en">,<head>(metadata, title, links, scripts) and<body>(visible content). - Element = start tag + content + end tag; void elements have no content or closing tag (
<br>,<hr>,<img>,<input>,<meta>,<link>). - Attributes: global (
id,class,style,title,hidden,tabindex,data-*) and element-specific (href,src,alt,type).idmust be unique in a document;classmay repeat. - Semantic HTML5 elements:
header,nav,main,section,article,aside,footer,figure/figcaption,time,mark. They improve accessibility (screen readers), SEO and maintainability over<div>soup. - Block vs inline: block-level elements (
div,p,h1-h6,ul,table,form) start on a new line and take full available width; inline elements (span,a,strong,em,img,input) flow within a line and ignore width/height (except replaced elements likeimg). - Lists: ordered
<ol>, unordered<ul>, description<dl>/<dt>/<dd>. - Tables:
table > caption, thead, tbody, tfoot > tr > th/td, withcolspan,rowspan, andscopeonthfor accessibility. Tables are for data, never for page layout. - Forms:
<form action method>wheremethod="GET"puts data in the query string (idempotent, bookmarkable, length-limited) andmethod="POST"puts it in the request body (for state-changing submissions). Controls:input(text, password, email, number, date, checkbox, radio, file, hidden, range, color),textarea,select/option,button. Thenameattribute — notid— is what gets submitted. - HTML5 form validation:
required,pattern,min/max,maxlength,type="email",novalidate; the Constraint Validation API givescheckValidity()andsetCustomValidity(). Client-side validation is for user experience only — the server must revalidate. - Media and graphics:
<audio>,<video>withcontrols/poster/<source>,<canvas>(scriptable raster drawing) and inline SVG (vector, DOM-addressable). - Other HTML5 APIs:
localStorage(persistent, ~5 MB per origin) andsessionStorage(per tab), Geolocation, Web Workers (background threads), History API (pushState), Drag-and-drop, Web Sockets. - Accessibility:
alttext on images,<label for>tied to controls, ARIA roles only when no semantic element exists. In India, the Rights of Persons with Disabilities Act, 2016 requires accessible government websites, and the GIGW (Guidelines for Indian Government Websites) standard, which maps to WCAG, is the applicable yardstick for government portals.
CSS: selectors, cascade and the box model
- CSS (Cascading Style Sheets) separates presentation from structure. Three ways to apply it: inline (
styleattribute), internal (<style>in head), external (<link rel="stylesheet">— preferred, cacheable, reusable). - Rule syntax:
selector { property: value; }. - Selectors: type (
p), class (.btn), id (#main), universal (*), attribute (input[type="text"]), descendant (div p), child (div > p), adjacent sibling (h2 + p), general sibling (h2 ~ p), pseudo-class (:hover,:focus,:first-child,:nth-child(2n),:not()), pseudo-element (::before,::after,::first-line). - Cascade order when several rules match: (1) importance (
!importantwins), (2) specificity, (3) source order (later wins). - Specificity is counted as (inline, id, class/attribute/pseudo-class, element/pseudo-element) and compared left to right. Inline style beats any selector;
!importantbeats inline. - Inheritance: text-related properties (
color,font-family,font-size,line-height,visibility) inherit; box properties (margin,padding,border,width,background) do not. Forced withinherit,initial,unset. - Box model: every element is content → padding → border → margin. Default
box-sizing: content-boxmeanswidthis the content width only;box-sizing: border-boxmakeswidthinclude padding and border — the usual global reset. - Margin collapse: adjacent vertical margins of block siblings collapse to the larger value; horizontal margins never collapse.
- display:
block,inline,inline-block(flows inline, respects width/height),none(removed from flow),flex,grid,table. Compare withvisibility: hidden(invisible but still occupies space) andopacity: 0(still clickable). - position:
static(default),relative(offset from its own place, space retained),absolute(removed from flow, positioned against nearest positioned ancestor),fixed(against viewport),sticky(relative until a scroll threshold, then fixed).z-indexorders overlapping positioned elements within a stacking context. - Float and clear:
float: left/righttakes an element partly out of flow for text wrap; the parent collapses unless cleared (clear: both,overflow: hidden, ordisplay: flow-root). Largely superseded by flexbox and grid for layout. - Flexbox is one-dimensional. Container:
display: flex,flex-direction,justify-content(main axis),align-items(cross axis),flex-wrap,gap. Item:flex-grow,flex-shrink,flex-basis(shorthandflex),align-self,order. - CSS Grid is two-dimensional:
display: grid,grid-template-columns/rows(withfr,repeat(),minmax(),auto-fit),grid-template-areas,gap,grid-column/grid-rowspans, plus the same alignment properties. Use grid for the page skeleton, flexbox for components inside it. - Units: absolute
px; relative%,em(parent font size),rem(root font size),vw/vh(viewport),ch.remis preferred for scalable, accessible type. - Responsive design: fluid widths,
max-width,<meta name="viewport" content="width=device-width, initial-scale=1">, and media queries@media (min-width: 768px) { ... }. Mobile-first means base styles target the small screen andmin-widthqueries add on — important in India where most traffic is on mid-range Android phones over 4G. - Other features:
transition,transform(translate,rotate,scale),@keyframesanimation, custom properties (--brand: #0a7; color: var(--brand)),calc(),@font-face, shadows and gradients,object-fit. - Specificity management: BEM naming, utility-first CSS, preprocessors (Sass/LESS variables, nesting, mixins) and CSS modules. Prefer low-specificity class selectors over ids so overrides stay possible.
JavaScript: language core
- JavaScript is a single-threaded, dynamically typed, interpreted (JIT-compiled) language standardised as ECMAScript; ES2015/ES6 was the major modernisation and a numbered edition ships each year.
- Types: primitives
number,string,boolean,undefined,null,symbol,bigint(copied by value) andobject(arrays, functions, dates — copied by reference). - Declarations:
varis function-scoped and hoisted asundefined;letandconstare block-scoped and hoisted but in the temporal dead zone until initialised (so access throwsReferenceError).constforbids reassignment, not mutation of the object's contents. - Hoisting: function *declarations* are hoisted whole and callable before their line; function *expressions* and arrow functions assigned to variables are not.
- Coercion and equality:
==coerces types (0 == "0"is true,null == undefinedis true),===compares type and value. Falsy values are exactlyfalse,0,-0,0n,"",null,undefined,NaN; everything else, including[]and{}, is truthy. - Functions: first-class values; default, rest (
...args) and destructured parameters; spread (...); template literals; optional chaining?.and nullish coalescing??(which falls back only onnull/undefined, unlike||). - Scope and closures: a closure is a function that keeps access to variables of the scope where it was created, even after that outer function returns — the basis of data privacy, module patterns, memoisation and once-only handlers.
- **
this:** in a normal function call it isundefinedin strict mode (the global object otherwise); in a method call it is the object before the dot; withnewit is the new instance; withcall/apply/bindit is what you pass. **Arrow functions have no ownthis** — they take it lexically, which is why they must not be used for object methods orprototypemethods that need the receiver. - Objects and prototypes: every object has an internal prototype link; property lookup walks the prototype chain.
classsyntax (ES6) withconstructor,extends,super, getters/setters and static members is sugar over prototypes. - Arrays: mutating (
push,pop,shift,unshift,splice,sort,reverse) vs non-mutating (slice,concat,map,filter,reduce,find,some,every,includes,flat).sort()without a comparator sorts as strings, so[10,9,1].sort()gives[1,10,9]. - Copying:
Object.assign({}, o)and{...o}are shallow; usestructuredClone(o)for a deep copy. - Error handling:
try/catch/finally,throw new Error(msg),Errorsubclasses. - Modules: ES modules
export/importwith<script type="module">(deferred and strict by default), against older CommonJSrequire/module.exports. - Strict mode (
"use strict") blocks implicit globals, duplicate parameters and silent failures.
DOM, events and the browser
- DOM (Document Object Model) is the browser's tree of objects built from parsed HTML; JavaScript reads and changes it, and the browser repaints.
- Selection:
getElementById,getElementsByClassName/TagName(live HTMLCollection),querySelector(first match),querySelectorAll(static NodeList). - Manipulation:
textContent(plain text, safe),innerHTML(parses HTML, can inject script — an XSS risk with untrusted input),createElement,append/appendChild,remove,classList.add/remove/toggle/contains,setAttribute,dataset,style.property. - Events:
addEventListener(type, handler, options); theeventobject carriestarget(what was clicked),currentTarget(what the listener is on),preventDefault()andstopPropagation(). - Propagation has three phases: capturing (window → target), target, bubbling (target → window, the default). Event delegation attaches one listener to a stable ancestor and checks
event.target— essential for lists whose rows are added later. - Rendering pipeline: parse HTML → DOM, parse CSS → CSSOM, combine into the render tree, layout/reflow (geometry), paint, composite. Changing geometry triggers reflow (costly); changing only colour or using
transform/opacityrepaints or composites (cheap). - Script loading: a plain
<script>in<head>blocks parsing;deferdownloads in parallel and runs in order after parsing;asyncruns as soon as it is fetched, order not guaranteed. Put blocking scripts at the end of<body>or usedefer. - Browser storage: cookies (sent with every request, ~4 KB),
localStorage,sessionStorage, IndexedDB (structured, large). - Security basics: the same-origin policy (scheme + host + port must match) restricts cross-origin reads; CORS headers let a server opt in. XSS is prevented by escaping output and avoiding
innerHTMLwith user data; CSRF by tokens andSameSitecookies; a Content-Security-Policy header blocks inline and foreign scripts.
Asynchronous JavaScript and the event loop
- JavaScript has one call stack. Long synchronous work freezes the page, so I/O is asynchronous.
- Event loop: the stack runs to completion; then all microtasks (promise callbacks,
queueMicrotask) drain; then one macrotask (timer, I/O, UI event) from the task queue is taken, and rendering may occur. Hence a resolved promise's.thenalways runs before asetTimeout(..., 0)queued earlier. - Callbacks came first and nest into "callback hell" with awkward error handling.
- Promise: an object in state
pending→fulfilledorrejected, consumed with.then,.catch,.finally;.thenreturns a new promise, so chains flatten nesting. - Combinators:
Promise.all(all succeed, else first rejection),Promise.allSettled(every outcome),Promise.race(first to settle),Promise.any(first fulfilment). - async/await: an
asyncfunction always returns a promise;awaitpauses that function only, not the thread. Errors usetry/catch. Independent awaits in sequence are a common slowdown — start them together andawait Promise.all. - **
fetch** returns a promise for aResponse; it rejects only on network failure, soresponse.ok/statusmust be checked for 404 or 500. Body is read withawait response.json(). - Timers:
setTimeout,setInterval(delays are a minimum, not a guarantee),requestAnimationFramefor animation. Debounce delays until input stops (search box); throttle caps the rate (scroll). - Web Workers give true parallelism for CPU work but have no DOM access and communicate by
postMessage.
Standards, tooling and workflow
- Standards bodies: WHATWG (HTML, DOM, Fetch living standards), W3C (CSS, WCAG, ARIA), ECMA TC39 (JavaScript, with a five-stage proposal process, Stage 0 strawperson to Stage 4 finished), IETF (HTTP).
- Browser support: feature-detect (
if ('fetch' in window)) rather than sniffing user agents; transpile with Babel and polyfill for older engines; vendor prefixes are handled by Autoprefixer. - Developer tools: Elements (live DOM and computed styles), Console, Sources with breakpoints, Network (waterfall, payload sizes), Lighthouse (performance, accessibility, SEO scores), device emulation.
- Build tooling: npm/pnpm, bundlers (Vite, webpack), minification, tree-shaking, code splitting, source maps, ESLint and Prettier.
- Performance: minimise and compress assets (gzip/Brotli), responsive images (
srcset, WebP/AVIF), lazy loading (loading="lazy"), font subsetting, fewer render-blocking resources, and Core Web Vitals (LCP, INP, CLS) as the measured targets. - Indian practice: pages are tuned for low-end Android and patchy mobile data; government and BFSI work follows GIGW/WCAG accessibility and the Digital Personal Data Protection Act, 2023 for consent notices and cookie banners (its rules were notified in 2025 and obligations are being phased in, so check the current commencement schedule).
Key points
- HTML - markup for structure and meaning; tags, attributes, nesting;
<!DOCTYPE html>forces standards mode. - Semantic elements -
header,nav,main,article,aside,footercarry meaning for accessibility and SEO. - Void elements -
br,hr,img,input,meta,linkhave no closing tag. - GET vs POST - GET sends data in the URL and is bookmarkable; POST sends it in the body for state changes.
- Box model - content + padding + border + margin;
border-boxmakeswidthinclude padding and border. - Specificity - inline > id > class/attribute/pseudo-class > element; ties broken by source order;
!importantoverrides all. - Inheritance - text properties inherit, box properties do not.
- position -
static,relative,absolute,fixed,sticky; only positioned elements respond toz-index. - Flexbox vs Grid - flexbox lays out one axis (components); grid lays out rows and columns together (page skeleton).
- Media query -
@media (min-width: 768px)with a viewport meta tag; mobile-first usesmin-width. - var/let/const -
varis function-scoped and hoisted asundefined;let/constare block-scoped with a temporal dead zone. - Closure - a function retaining its creation scope's variables after the outer function has returned.
- **
this** - decided by how a function is called; arrow functions inherit it lexically and have none of their own. - == vs === -
==coerces types,===compares type and value; prefer===. - Event bubbling and delegation - events rise from target to root; one ancestor listener can serve dynamic children.
- Event loop - stack → drain all microtasks (promises) → one macrotask (timers, events); so promises beat
setTimeout(0). - async/await - sugar over promises;
awaitsuspends only the async function, and errors are caught withtry/catch. - Security - same-origin policy plus CORS; escape output and avoid
innerHTMLwith user data to stop XSS.
Formulas and examples
style attribute; b = number of id selectors; c = number of class, attribute and pseudo-class selectors; d = number of element and pseudo-element selectors. Compare a, then b, then c, then d (no carrying between columns). Unitless count, not a single score.box-sizing: content-box) = width + 2 × padding + 2 × border; horizontal space occupied = that + 2 × margin. Units: px, em, rem or %.box-sizing: border-box) = width (padding and border inside it); content width = width − 2 × padding − 2 × border.fr = container inline size − fixed track sizes − (number of gaps) × gap; each 1fr track = free space ÷ Σ fr.Example 1 — Specificity contest. Which colour wins for <p id="intro" class="lead"> inside <div id="main">?
p { color: black; } /* (0,0,0,1) */
.lead { color: blue; } /* (0,0,1,0) */
#main p { color: green; } /* (0,1,0,1) */
#intro { color: red; } /* (0,1,0,0) */
div#main p.lead { color: teal; } /* (0,1,1,2) */
- Compare b (ids):
p0,.lead0,#main p1,#intro1,div#main p.lead1 → last three survive. - Compare c (classes): 0, 0, 1 →
div#main p.leadwins with (0,1,1,2). Text is teal. - Add
style="color: orange"on the paragraph and orange wins (a = 1). Add!importantto.leadand blue wins over even the inline style.
Example 2 — Box model arithmetic. A card has width: 300px; padding: 20px; border: 5px; margin: 10px.
content-box: rendered width = 300 + 2×20 + 2×5 = 350 px; space occupied = 350 + 2×10 = 370 px. Three such cards side by side need 3 × 370 = 1,110 px — they overflow a 1,024 px viewport.border-box: rendered width = 300 px, content width = 300 − 40 − 10 = 250 px; space occupied = 320 px; three cards = 960 px, which fits in 1,024 px.
Example 3 — Flex and grid sizing. A flex container is 600 px wide with gap: 0 and three items of flex-basis: 100px; grow factors are 1, 2 and 3.
- Free space = 600 − 300 = 300 px. Shares = 300 × 1/6 = 50, 300 × 2/6 = 100, 300 × 3/6 = 150.
- Final widths = 150 px, 200 px, 250 px (sum 600 px). ✔
- Now a grid:
width: 600px; gap: 10px; grid-template-columns: 200px 1fr 2fr. Gaps = 2 × 10 = 20 px; free space = 600 − 200 − 20 = 380 px.1fr= 380/3 ≈ 126.67 px,2fr≈ 253.33 px. Tracks ≈ 200, 126.67, 253.33 px.
Example 4 — Event loop order. Predict the output:
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
(async () => { console.log('4'); await null; console.log('5'); })();
console.log('6');
- Synchronous pass:
1, then the timer is queued, then the promise callback is queued as a microtask, then the async function runs to itsawaitprinting4and queuing its continuation, then6. - Microtask queue drains in order:
3, then5. - Finally the macrotask:
2. - Output: 1, 4, 6, 3, 5, 2.
**Example 5 — Closures and var in a loop.** A GST-rate button list for an Indian billing page:
const rates = [5, 18, 40]; // GST slabs since 22 Sep 2025
for (var i = 0; i < rates.length; i++) {
setTimeout(() => console.log(rates[i]), 0); // undefined ×3
}
for (let j = 0; j < rates.length; j++) {
setTimeout(() => console.log(rates[j]), 0); // 5, 18, 40
}
function makeGst(rate) { // closure over `rate`
return amount => +(amount * rate / 100).toFixed(2);
}
const gst18 = makeGst(18);
console.log(gst18(1500)); // 270
var iis one function-scoped binding; by the time the callbacks runiis 3 andrates[3]isundefined.let jcreates a fresh binding each iteration, so each closure captures its own value.gst18(1500)= 1500 × 18 / 100 = ₹270, so the invoice total is ₹1,770.
| Concern | HTML | CSS | JavaScript |
|---|---|---|---|
| Role | Structure and meaning | Presentation and layout | Behaviour and logic |
| Nature | Markup, declarative | Declarative rule set | Imperative programming language |
| Failure mode | Unknown tags ignored, page still renders | Invalid declaration skipped, rest applies | Uncaught error can stop the whole script |
| Error style | Forgiving, auto-corrected by parser | Forgiving | Throws at runtime |
| Standard | HTML5 (WHATWG living standard) | CSS3 modules (W3C) | ECMAScript (TC39, annual edition) |
localStorage | sessionStorage | Cookie | |
|---|---|---|---|
| Lifetime | Until explicitly cleared | Until the tab closes | Until its expiry date |
| Size per origin | About 5 MB | About 5 MB | About 4 KB |
| Sent to server | No | No | Yes, with every matching request |
| Typical use | Theme, draft form data | One-visit wizard state | Session id, auth token |
Where it is used
- IT services and product companies: front-end and full-stack roles at TCS, Infosys, Wipro, HCLTech, Accenture, Cognizant, Zoho, Freshworks and Zoho/Zomato-class product teams; the first screening round is usually HTML/CSS/JS fundamentals before any framework.
- Government and public digital infrastructure: UIDAI, GSTN, IRCTC, DigiLocker, UMANG and state e-governance portals, built to GIGW/WCAG accessibility and tested on low-bandwidth Android.
- BFSI and fintech: net-banking and UPI dashboards, Razorpay/Paytm/PhonePe checkout widgets and payment pages, where form validation, responsive layout and XSS/CSRF hardening are contractual requirements.
- E-commerce and consumer apps: Flipkart, Myntra, Swiggy and Nykaa web storefronts; Core Web Vitals (LCP, INP, CLS) drive revenue and search ranking.
- Job roles: front-end developer, UI developer, full-stack developer, web designer, QA automation engineer (Selenium/Playwright use CSS and XPath selectors), WordPress/Shopify developer, email-template developer, technical SEO analyst.
- Internal tooling and reporting: HTML/CSS/JS dashboards and report viewers inside manufacturing, BPO and healthcare firms, and hybrid mobile apps (Cordova, Capacitor, Electron) that run web code in a shell.
Interview questions
- Q: What is the difference between
visibility: hiddenanddisplay: none? A:visibility: hiddenkeeps the element's box in the layout so its space remains reserved;display: noneremoves it from the render tree entirely, so other content moves up. - Q: Why do most projects set
box-sizing: border-boxglobally? A: Because thenwidthalready includes padding and border, so adding padding does not break a grid or push elements out of a container. - Q: How is CSS specificity decided when two rules conflict? A: Compare inline style, then id count, then class/attribute/pseudo-class count, then element count; if specificity ties, the later rule wins, and
!importantbeats everything else. - Q: When would you use flexbox rather than grid? A: Flexbox for a single row or column whose items size themselves — a navbar or toolbar; grid when you need defined rows and columns at once, like a page skeleton or card gallery.
- Q: Explain hoisting with
var,letandconst. A: All three are hoisted, butvaris initialised toundefinedand readable, whileletandconstsit in the temporal dead zone and throw aReferenceErroruntil their declaration executes. - Q: What is a closure and give one real use? A: A function that still accesses variables from the scope in which it was defined after that scope has returned; used for private counters, memoised caches, and pre-configured handlers such as a per-row delete button.
- Q: How does
thisbehave in an arrow function inside an object method? A: The arrow function has no ownthis, so it inherits the enclosing scope's — which is why arrow functions are wrong for object or prototype methods but ideal for callbacks inside a method. - Q: Why does a promise callback run before
setTimeout(fn, 0)? A: Promise callbacks are microtasks and the entire microtask queue drains after the current stack empties, whereas a timer is a macrotask picked up only in the next event-loop turn. - Q: What is event delegation and why is it useful? A: One listener on a parent handles events bubbling up from children, checking
event.target; it covers elements added later and saves hundreds of listeners on a long table. - Q: Does
fetchreject on a 404? A: No — it rejects only on a network-level failure, so you must testresponse.okorresponse.statusand throw yourself. - Q: Difference between
deferandasyncon a script tag? A: Both download without blocking parsing;deferexecutes after parsing in document order, whileasyncexecutes the moment it arrives, in unpredictable order. - Q: How do you prevent XSS in DOM code? A: Write user data with
textContentorcreateTextNodeinstead ofinnerHTML, escape anything that must be HTML, and add a Content-Security-Policy header; server-side output encoding is the real defence. - Q: Why is client-side form validation not enough? A: It can be bypassed by disabling JavaScript or posting directly to the endpoint, so the server must revalidate every field before trusting it.
Common mistakes
- Forgetting the viewport meta tag and then wondering why media queries do nothing on a phone.
- Fighting the cascade with
!importantand id selectors instead of fixing specificity, which makes later overrides impossible. - Using
idfor repeated elements, or submitting a form and finding no data because controls haveidbut noname. - Ignoring the box model in exam calculations — leaving out padding, border or margin, or applying
border-boxrules to acontent-boxelement. - Assuming
varin a loop gives each callback its own copy, or using an arrow function as an object method and losingthis. - Treating
awaitas if it blocked everything, or awaiting independent requests one after another instead ofPromise.all. - Comparing with
==, or testing truthiness of[]/"0"and expecting them to be falsy. - Writing user input into
innerHTML, and relying on HTML5required/patternas the only validation. - Using tables for layout, skipping
alttext and<label>, and failing an accessibility audit under GIGW/WCAG.
Related topics
Front-end frameworks: React basics · REST APIs · Authentication and authorisation: sessions, OAuth and JWT · Back-end development with Node.js · Caching, queues and CDNs · System design basics for freshers