50 Essential HTML, CSS, and JavaScript Interview Questions
50 Essential HTML, CSS, and JavaScript Interview Questions
Table of Contents
1. JavaScript Core Concepts
4. CSS Fundamentals
5. Layout and Positioning
6. Web Design Considerations
7. Additional Topics
2. ⚡ Event Handling
Use event delegation
Debounce/throttle high-frequency events
4. ⚡ Memory Management
Avoid memory leaks
Properly scope variables
Clean up unused resources
🛠️ Practical Techniques:
javascript
Copy
javascript Copy
📈 Performance Measurement:
Use console.time() and console.timeEnd()
css
Copy
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* Three columns */
grid-template-rows: 100px auto 100px; /* Three rows */
gap: 20px; /* Gap between grid items */
}
grid-template-
Defines column sizes grid-template-columns: repeat(3, 1fr)
columns
grid-template-
Defines row sizes grid-template-rows: 100px auto 50px
rows
css
Copy
.dashboard {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header header"
"sidebar content content content"
"footer footer footer footer";
min-height: 100vh;
gap: 20px;
}
.container {
display: flex;
flex-direction: row; /* Default: items in a row */
justify-content: space-between; /* Horizontal spacing */
align-items: center; /* Vertical alignment */
flex-wrap: wrap; /* Allow items to wrap to next line */
}
Container
Purpose Values
Property
Cross-axis
align-items flex-start , flex-end , center , stretch , baseline
alignment
Space between
gap 10px , 1rem
items
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
css Copy
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 0 1 calc(33.333% - 20px);
display: flex;
flex-direction: column;
}
.card-body {
flex: 1 0 auto;
}
.card-footer {
margin-top: auto;
}
Navigation Menu:
css
Copy
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
.nav-links {
display: flex;
gap: 1rem;
}
/* Responsive toggle */
@media (max-width: 768px) {
.navbar {
flex-direction: column;
}
.nav-links {
flex-direction: column;
width: 100%;
}
}
Overall page layout Grid Designed for 2D layouts with both rows and columns
Card layouts with variable content Flexbox Better for handling unknown content sizes
Responsive design without media queries Grid minmax() , auto-fill , and auto-fit
Form controls alignment Flexbox Simpler for aligning related form elements
javascript
Copy
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Handle Date
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle Array
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item));
}
// Handle Object
if (obj instanceof Object) {
const copy = {};
Object.keys(obj).forEach(key => {
copy[key] = deepClone(obj[key]);
});
return copy;
}
3. Implement Promise.all()
javascript
Copy
function myPromiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
if (promises.length === 0) {
resolve(results);
return;
}
javascript Copy
function flattenArray(arr) {
return arr.reduce((flat, item) => {
return flat.concat(Array.isArray(item) ? flattenArray(item) : item);
}, []);
}
// Usage
flattenArray([1, [2, [3, 4], 5], 6]); // [1, 2, 3, 4, 5, 6]
✈️ Reading Guide: This document is organized for easy in-flight reading. Each question includes a
concise explanation and practical code examples. The topics progress from fundamental to advanced
concepts. Take breaks between sections to help with retention.
⚠️ Important Details:
Only declarations are hoisted, not initializations
javascript Copy
console.log(foo); // undefined
var foo = 1;
console.log(foo); // 1
// Visualized as:
var foo;
console.log(foo); // undefined
foo = 1;
console.log(foo); // 1
javascript Copy
console.log(bar); // ReferenceError
let bar = 'value';
Function declarations vs. expressions:
Function declarations are fully hoisted (both declaration and definition), while function expressions are
only partially hoisted.
javascript Copy
console.log(declared()); // Works
function declared() {
return 'Declared function';
}
console.log(expr); // undefined
console.log(expr()); // TypeError: expr is not a function
var expr = function() {
return 'Function expression';
};
💡 Key Concept: These keywords have different scoping, hoisting, redeclaration, and reassignment rules.
📋 Comparison Chart:
Hoisting Yes, initialized as undefined Yes, but not initialized Yes, but not initialized
⚠️ Common Pitfall: Using var in loops creates a single variable for all iterations due to function scope.
💡 Key Concept: == performs type coercion before comparison, while === compares both value and
📊 Examples:
javascript
Copy
🚀 Best Practice: Use === by default to avoid unexpected type coercion. Only use == when you
specifically want type coercion (rare cases).
🔄 Key Components:
Call Stack: Tracks the current function being executed
Callback Queue: Holds callbacks from completed async operations
Microtask Queue: High-priority queue for Promises (processed before the Callback Queue)
Web APIs: Browser features that handle async operations outside JavaScript's main thread
📈 Execution Flow:
1. Execute synchronous code on call stack
2. When stack is empty, process all microtasks
🧪 Example:
javascript Copy
// Output order:
// Start
// End (Call stack now empty)
// Promise (Process microtask queue)
// Timeout (Process callback queue)
⚠️ Common Misconception: setTimeout(fn, 0) doesn't execute immediately; it still goes through the
event loop after the call stack is empty.
🏗️ Reference Types:
Object: Collections of properties (e.g., {} , new Object() )
Array: Ordered lists (e.g., [] , new Array() )
🔍 Type Checking:
javascript
Copy
⚠️ Gotchas:
typeof null returns 'object' (a historical bug)
Primitive wrapper objects ( new String() , new Number() ) have type 'object'
💡 Key Concept: The value of this is determined by how a function is called, not where it's defined
(except for arrow functions).
Event handler The element that triggered the event button.onclick = function() {...}
🧪 Examples:
javascript
Copy
// Global context
console.log(this); // Window (browser) or global (Node)
// Object method
const user = {
name: 'Alice',
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
user.greet(); // "Hello, I'm Alice"
// Constructor
function User(name) {
this.name = name;
this.sayHi = function() {
console.log(`Hi, I'm ${this.name}`);
};
}
const bob = new User('Bob');
bob.sayHi(); // "Hi, I'm Bob"
// Explicit binding
function introduce(greeting) {
console.log(`${greeting}, I'm ${this.name}`);
}
introduce.call(user, 'Howdy'); // "Howdy, I'm Alice"
introduce.apply(user, ['Hello']); // "Hello, I'm Alice"
const boundIntroduce = introduce.bind(user);
boundIntroduce('Hey'); // "Hey, I'm Alice"
// Arrow functions
const team = {
name: 'Developers',
members: ['Alice', 'Bob'],
showMembers() {
// Arrow function inherits `this` from showMembers
this.members.forEach(member => {
console.log(`${member} is in team ${this.name}`);
});
}
};
team.showMembers();
// "Alice is in team Developers"
// "Bob is in team Developers"
⚠️ Common Pitfalls:
Losing this context when passing methods as callbacks
javascript Copy
const john = {
age: 42,
getAge: function() {
return this.age;
},
};
console.log(john.getAge()); // 42
Common Uses:
function foo() {
console.log('Function declaration');
}
Function Expressions:
javascript Copy
javascript
Copy
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
javascript Copy
function outerFunction() {
let outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable); // 'I am outside!'
}
innerFunction();
}
Global Scope:
Function Scope:
Block Scope:
// Global scope
var globalVar = 'I am global';
function myFunction() {
// Function scope
var functionVar = 'I am in a function';
if (true) {
// Block scope
let blockVar = 'I am in a block';
console.log(blockVar); // Accessible
}
// console.log(blockVar); // Error
}
HTML Essentials
⚠️ Common Misuse:
Using <div> when a semantic element would be more appropriate
Using elements for their visual style rather than their semantic meaning
Accessibility Attributes
💡 Key Concept: HTML provides attributes to improve accessibility for users with disabilities.
Attribute Purpose Example
aria-
Links to extended description <input aria-describedby="hint">
describedby
🚀 Best Practices:
Use semantic HTML elements whenever possible before resorting to ARIA
Event delegation uses a single event listener on a parent element to manage events on its child elements,
utilizing event bubbling for efficiency.
Benefits:
javascript
Copy
📋 Storage Comparison:
Feature Cookies localStorage sessionStorage
🛠️ Usage Examples:
javascript
Copy
// Cookies
document.cookie = "username=John; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/; Secure; SameSi
⚠️ Security Considerations:
Never store sensitive information (passwords, credit cards) in client-side storage
Use HttpOnly and Secure flags for cookies with sensitive data
<script> :
<script defer> :
html
Copy
<script src="main.js"></script>
<script async src="async.js"></script>
<script defer src="defer.js"></script>
javascript
Copy
javascript
Copy
mouseover:
Key Components:
javascript
Copy
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Event-based approach
More verbose syntax
fetch():
Promise-based API
CSS Fundamentals
🛠️ Practical Uses:
Containing floated elements (prevent float collapse)
Preventing margin collapsing between elements
📝 Example:
css
Copy
.container {
/* Creates a BFC */
overflow: hidden;
Margins/Padding All sides respected All sides respected Only horizontal sides affect layout
24. How Do relative, fixed, absolute, sticky, and static Positioning Differ?
💡 Key Concept: The position property determines how an element is positioned in the document
flow.
📋 Positioning Types:
Nearest positioned
absolute Removed Yes No (unless z-index)
ancestor
In flow until
sticky Nearest scrolling ancestor Yes, until "stuck" Yes
threshold
🔄 Position Examples:
css
Copy
/* Default positioning */
.static {
position: static;
/* top, right, bottom, left have no effect */
}
⚠️ Common Pitfalls:
absolute elements are positioned relative to the viewport if no ancestor has positioning
fixed elements can behave unexpectedly with CSS transforms on ancestors
Advantages:
27. What Should You Consider When Designing for Multilingual Websites?
💡 Key Concept: Designing multilingual websites involves technical, cultural, and UX considerations to
ensure the site works well across different languages and regions.
🌐 Technical Implementation:
1. HTML Language Attributes:
html
Copy
Copy
domain.com/en/page (path-based)
en.domain.com/page (subdomain-based)
domain.com/page?lang=en (parameter-based)
2. Reading Direction:
Support both LTR (left-to-right) and RTL (right-to-left) layouts
.container {
padding-inline-start: 20px; /* Works for both LTR and RTL */
}
4. Cultural Considerations:
Colors have different meanings across cultures
Icons may need adaptation (e.g., mailbox designs vary globally)
⚠️ Common Pitfalls:
Hard-coding strings instead of using translation files
Use Cases:
Array Destructuring:
javascript
Copy
Object Destructuring:
javascript
Copy
const { name, age, ...other } = { name: 'John', age: 30, city: 'New York', job: 'Developer' };
// name: 'John', age: 30, other: { city: 'New York', job: 'Developer' }
Array Operations:
javascript
Copy
// Copying arrays
const original = [1, 2, 3];
const copy = [...original];
// Merging arrays
const merged = [...array1, ...array2];
Object Operations:
javascript
Copy
// Copying objects
const original = { a: 1, b: 2 };
const copy = { ...original };
// Merging objects
const merged = { ...obj1, ...obj2 };
Function Arguments:
javascript
Copy
javascript
Copy
Constructor Function:
javascript
Copy
function Person(name) {
this.name = name;
}
const john = new Person('John');
Object.create():
javascript
Copy
javascript
Copy
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
javascript
Copy
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
speak() {
console.log(`${this.name} barks.`); // Override parent method
}
}
javascript Copy
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Additional Topics
const fs = require('fs');
const data = fs.readFileSync('large-file.txt', 'utf8');
console.log(data); // Blocks until file is read
console.log('End of the program');
Asynchronous Functions:
Allow the program to continue running without waiting for task completion
Commonly used for network requests, file I/O, timers, and animations
javascript
Copy
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data)) // Non-blocking
.catch((error) => console.error(error));
console.log('End of program');
Disadvantages:
36. How Do You Iterate Over Object Properties and Array Elements?
For Objects:
javascript
Copy
// for...in loop
for (const key in obj) {
if (Object.hasOwn(obj, key)) {
console.log(`${key}: ${obj[key]}`);
}
}
// Object.keys()
Object.keys(obj).forEach(key => {
console.log(`${key}: ${obj[key]}`);
});
// Object.entries()
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
For Arrays:
javascript
Copy
// for loop
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// forEach method
arr.forEach((item, index) => {
console.log(item, index);
});
// for...of loop
for (const item of arr) {
console.log(item);
}
Concise Syntax:
javascript
Copy
// Traditional function
const double = function(x) {
return x * 2;
};
// Arrow function
const double = x => x * 2;
Lexical this :
javascript
Copy
function Person() {
this.age = 0;
Asynchronous Code:
Non-blocking execution
Operations can run in parallel
Results processed when available
Async Techniques:
javascript
Copy
// Callbacks
function fetchData(callback) {
setTimeout(() => {
callback('Data');
}, 1000);
}
// Promises
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
// Async/Await
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
🔄 Debouncing:
Delays function execution until after a specified period of inactivity
Resets the timer whenever the event fires again
Ensures function only runs once after rapid successive calls stop
⏱️ Debouncing Implementation:
javascript
Copy
return function(...args) {
// Clear previous timeout
clearTimeout(timeoutId);
🔄 Throttling:
Executes the function at a regular interval, regardless of how many times the event is fired
⏱️ Throttling Implementation:
javascript
Copy
return function(...args) {
// If we're not throttled, execute the function
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
window.addEventListener('scroll', throttledScroll);
📊 Comparison:
Feature Debounce Throttle
Example use cases Search inputs, resize events Scroll events, game loops
Behavior with rapid events Executes once at end Executes regularly throughout
🚀 Real-world Applications:
Debounce: Autocomplete, form validation, resize handlers, save buttons
Throttle: Infinite scroll, scroll animations, mousemove events, game input
Directly iterable
Better performance for frequent additions/removals
Plain Objects:
No size property
Not directly iterable
Better for simple key-value storage
javascript
Copy
// Map
const map = new Map();
map.set('key1', 'value1');
map.set({}, 'value2');
console.log(map.size); // 2
// Object
const obj = {};
obj.key1 = 'value1';
obj[{}] = 'value2'; // {} becomes '[object Object]'
.call:
function sum(a, b) {
return a + b;
}
sum.call(null, 1, 2); // 3
.apply:
javascript Copy
function sum(a, b) {
return a + b;
}
sum.apply(null, [1, 2]); // 3
Type is 'object'
Must be assigned
undefined:
Type is 'undefined'
Undeclared:
let a; // undefined
const b = null; // null
console.log(c); // ReferenceError (undeclared)
43. What are the Differences Between ES2015 Classes and ES5 Constructors?
ES5 Constructor:
javascript Copy
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
ES2015 Class:
javascript Copy
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, I'm ${this.name}`);
}
}
Key Differences:
Key Types:
Map/Set: Accept any value as keys
Memory Management:
Map/Set: Strong references prevent garbage collection
Enumeration:
Map/Set: Keys can be enumerated
WeakMap/WeakSet: Keys cannot be enumerated
Size Property:
Map/Set: Have a size property
WeakMap/WeakSet: No size property
Examples:
css Copy
/* Block layout */
.container { display: block; }
/* Grid layout */
.grid-container { display: grid; }
/* Hide element */
.hidden { display: none; }
This is particularly useful in cases where methods are passed as callbacks or event handlers.
function fetchData(callback) {
// Simulate async operation (e.g., API request)
setTimeout(() => {
const data = { name: 'John', age: 30 };
callback(data); // Execute callback with result
}, 1000);
}
fetchData((data) => {
console.log(data); // { name: 'John', age: 30 }
});
Key characteristics:
48. What's the Difference Between function Person(){}, const person = Person(), and
const person = new Person()?
function Person() {}:
this inside the function refers to the global object (or undefined in strict mode)
Array methods:
javascript
Copy
// Traditional approach
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number) {
return number * 2;
});
Event handlers:
javascript Copy
increment() {
this.count++;
}
}
Effects:
Width and height include content, padding, and border (but not margin)
Makes sizing more intuitive (add padding without changing dimensions)
Comparison:
Advantages:
⭐ Preparation Strategies
1. Focus on fundamentals: Interviewers often look for solid understanding of core concepts over
trendy frameworks.
2. Practice explaining concepts verbally: Record yourself explaining key concepts in simple terms.
3. Code on paper first: Practice writing code without IDE assistance to simulate whiteboard interviews.
4. Review your own projects: Be ready to discuss architectural decisions and challenges from your past
work.
5. Create cheat sheets: Make your own concise summary cards for quick review before interviews.
2. Think aloud: Explain your thought process as you work through solutions.
3. Start with a naive solution: Begin with a working solution, then optimize.
4. Test your code: Walk through your solution with test cases before declaring it complete.
5. Be honest about what you don't know: Say "I don't know, but here's how I'd figure it out" instead
of guessing.
Coding challenge Break down the problem, consider edge cases, test your solution
System design Clarify requirements, start with high-level architecture, then dive deeper
Behavioral questions Use the STAR method (Situation, Task, Action, Result)
3. Reflection: Consider what went well and what could be improved for next time.
Good luck with your interviews! Remember that preparation builds confidence, and confidence leads to
success.