0% found this document useful (0 votes)
19 views55 pages

50 Essential HTML, CSS, and JavaScript Interview Questions

The document provides a comprehensive guide to essential HTML, CSS, and JavaScript interview questions, covering core concepts, performance optimization tips, and practical coding examples. It includes sections on JavaScript functions, DOM manipulation, CSS layout techniques using Grid and Flexbox, and common coding challenges. Additionally, it highlights key differences between JavaScript variable declarations and data types, along with best practices for coding interviews.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views55 pages

50 Essential HTML, CSS, and JavaScript Interview Questions

The document provides a comprehensive guide to essential HTML, CSS, and JavaScript interview questions, covering core concepts, performance optimization tips, and practical coding examples. It includes sections on JavaScript functions, DOM manipulation, CSS layout techniques using Grid and Flexbox, and common coding challenges. Additionally, it highlights key differences between JavaScript variable declarations and data types, along with best practices for coding interviews.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

50 Essential HTML, CSS, and JavaScript Interview Questions

A comprehensive guide for web development interviews

Table of Contents
1. JavaScript Core Concepts

2. JavaScript Functions and Scope


3. DOM and Browser APIs

4. CSS Fundamentals
5. Layout and Positioning
6. Web Design Considerations

7. Additional Topics

JavaScript Performance Tips

Optimizing JavaScript Performance


💡 Key Areas for Optimization:
1. ⚡ DOM Manipulations
Batch DOM operations
Use document fragments

Reduce reflows and repaints

2. ⚡ Event Handling
Use event delegation
Debounce/throttle high-frequency events

Remove unused event listeners

3. ⚡ Data Structures & Algorithms


Choose appropriate data structures

Optimize loops and iterations


Consider time complexity

4. ⚡ Memory Management
Avoid memory leaks
Properly scope variables
Clean up unused resources

🛠️ Practical Techniques:

javascript
Copy

// ❌ Inefficient (multiple DOM operations)


for (let i = 0; i < 1000; i++) {
container.innerHTML += `<div>${i}</div>`;
}

// ✅ Optimized (single DOM operation)


const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const div = document.createElement('div');
div.textContent = i;
fragment.appendChild(div);
}
container.appendChild(fragment);

javascript Copy

// ❌ Inefficient (causes layout thrashing)


const boxes = document.querySelectorAll('.box');
boxes.forEach(box => {
const height = box.offsetHeight; // Forces layout
box.style.width = `${height}px`; // Forces another layout
});

// ✅ Optimized (batches reads and writes)


const boxes = document.querySelectorAll('.box');
const heights = Array.from(boxes).map(box => box.offsetHeight); // Read phase
boxes.forEach((box, i) => {
box.style.width = `${heights[i]}px`; // Write phase
});

📈 Performance Measurement:
Use console.time() and console.timeEnd()

Leverage Browser DevTools Performance panel

Test with realistic data volumes


Profile in multiple browsers

CSS Grid & Flexbox Reference

CSS Grid Layout


💡 Key Concept: CSS Grid is a two-dimensional layout system ideal for both overall page layout and
complex component structure.

🛠️ Basic Grid Container:

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 */
}

📋 Essential Grid Properties:

Container Property Purpose Example

grid-template-
Defines column sizes grid-template-columns: repeat(3, 1fr)
columns

grid-template-
Defines row sizes grid-template-rows: 100px auto 50px
rows

grid-template- grid-template-areas: "header header"


Names grid areas
areas "sidebar content"

Default size for auto-created


grid-auto-columns grid-auto-columns: 100px
columns

Default size for auto-created


grid-auto-rows grid-auto-rows: min-content
rows

gap Space between items gap: 20px

justify-items Horizontal alignment justify-items: center

align-items Vertical alignment align-items: start


 
Item Property Purpose Example

grid-column Column start/end grid-column: 1 / 3

grid-row Row start/end grid-row: 2 / span 2

grid-area Named area placement grid-area: header

justify-self Horizontal self-alignment justify-self: end

align-self Vertical self-alignment align-self: center


 

🔍 Complex Grid Example:

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;
}

.header { grid-area: header; }


.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer { grid-area: footer; }

CSS Flexbox Layout


💡 Key Concept: Flexbox is a one-dimensional layout system ideal for distributing space among items in
a container, even when their size is unknown or dynamic.

🛠️ Basic Flex Container:


css Copy

.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 */
}

📋 Essential Flexbox Properties:

Container
Purpose Values
Property

flex- Direction of flex


row , row-reverse , column , column-reverse
direction items

justify- flex-start , flex-end , center , space-between , space-


Main-axis alignment
content around , space-evenly

Cross-axis
align-items flex-start , flex-end , center , stretch , baseline
alignment

Whether items can


flex-wrap nowrap , wrap , wrap-reverse
wrap

Space between
gap 10px , 1rem
items
 

Item Property Purpose Example

flex-grow Growth factor flex-grow: 1

flex-shrink Shrink factor flex-shrink: 0

flex-basis Initial size flex-basis: 200px

flex Shorthand flex: 1 0 auto

align-self Individual alignment align-self: flex-end

order Position in layout order: -1


 

🔍 Common Flexbox Patterns:


Centering an Element:
css Copy

.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

Card Layout with Variable Height:

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%;
}
}

Grid vs Flexbox: When to Use Each


Need Better Solution Why

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

Complex alignment needs Grid Precise control over both dimensions

One-dimensional layouts Flexbox Simpler for single row/column arrangements

Dynamic number of items Flexbox Naturally handles varying item counts

Overlapping elements Grid Can position items in same grid cell

Responsive design without media queries Grid minmax() , auto-fill , and auto-fit

Form controls alignment Flexbox Simpler for aligning related form elements
 

Common JavaScript Interview Coding Questions


1. Implement a Debounce Function

javascript
Copy

function debounce(func, wait) {


let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

2. Create a Deep Clone Function


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;
}

throw new Error(`Unable to copy object: ${obj}`);


}

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;
}

promises.forEach((promise, index) => {


Promise.resolve(promise)
.then(result => {
results[index] = result;
completed++;

if (completed === promises.length) {


resolve(results);
}
})
.catch(error => {
reject(error);
});
});
});
}

4. Flatten a Nested Array

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.

JavaScript Core Concepts

1. What Is Hoisting in JavaScript?


💡 Key Concept: Hoisting moves variable and function declarations to the top of their scope during
compilation.

⚠️ Important Details:
Only declarations are hoisted, not initializations

Function declarations are fully hoisted (with their body)


Variables declared with let and const are hoisted but remain in the "temporal dead zone" until
declaration

Example with var :

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

Variables declared with let , const , and class :


These are hoisted but remain uninitialized, causing a ReferenceError if accessed before declaration.

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';
};

2. How Do let , var , and const Differ?

💡 Key Concept: These keywords have different scoping, hoisting, redeclaration, and reassignment rules.
📋 Comparison Chart:

Feature var let const

Scope Function or global Block Block

Hoisting Yes, initialized as undefined Yes, but not initialized Yes, but not initialized

Redeclaration Allowed Not allowed Not allowed

Reassignment Allowed Allowed Not allowed

Initialization Optional Optional Required


 

⚠️ Common Pitfall: Using var in loops creates a single variable for all iterations due to function scope.

3. What Is the Difference Between == and === ?

💡 Key Concept: == performs type coercion before comparison, while === compares both value and

type without conversion.

📊 Examples:
javascript
Copy

// Loose equality (==)


42 == '42' // true (string '42' is converted to number 42)
0 == false // true (boolean false is converted to number 0)
null == undefined // true (special case in the spec)

// Strict equality (===)


42 === '42' // false (different types: number vs string)
0 === false // false (different types: number vs boolean)
null === undefined // false (different types)

🚀 Best Practice: Use === by default to avoid unexpected type coercion. Only use == when you
specifically want type coercion (rare cases).

4. What Is the Event Loop in JavaScript?


💡 Key Concept: The event loop allows JavaScript to execute non-blocking asynchronous code despite
being single-threaded.

🔄 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

3. Render UI updates if needed


4. Process one task from the callback queue
5. Repeat

🧪 Example:
javascript Copy

console.log('Start'); // 1. Synchronous: Logs immediately

setTimeout(() => { // 2. Async: Scheduled in Web APIs


console.log('Timeout'); // Goes to Callback Queue when timer completes
}, 0);

Promise.resolve().then(() => { // 3. Async: Creates a microtask


console.log('Promise'); // Goes to Microtask Queue
});

console.log('End'); // 4. Synchronous: Logs immediately

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

5. What Are the Different Data Types in JavaScript?


💡 Key Concept: JavaScript has primitive types (stored by value) and objects (stored by reference).
🧩 Primitive Types:
Number: Both integers and floating-point (e.g., 42 , 3.14 )

String: Text data (e.g., 'hello' , "world" , `template` )

Boolean: true or false

null: Intentional absence of value

undefined: Variable declared but not assigned


Symbol: Unique, immutable value (e.g., Symbol('id') )

BigInt: Large integers (e.g., 9007199254740991n )

🏗️ Reference Types:
Object: Collections of properties (e.g., {} , new Object() )
Array: Ordered lists (e.g., [] , new Array() )

Function: Callable objects (e.g., function() {} , () => {} )

Date: Date and time (e.g., new Date() )

RegExp: Regular expressions (e.g., /\d+/ , new RegExp('\d+') )

Map/Set: Collections with unique keys/values

WeakMap/WeakSet: Collections with weak references

🔍 Type Checking:

javascript
Copy

// Using typeof (works well for primitives except null)


typeof 42; // 'number'
typeof 'hello'; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof null; // 'object' (⚠️ historical bug)
typeof {}; // 'object'
typeof []; // 'object' (⚠️ arrays are objects)
typeof function() {}; // 'function'

// Better checks for specific object types


Array.isArray([]); // true
obj instanceof Array; // true if obj is an array
Object.prototype.toString.call([]); // '[object Array]'

⚠️ Gotchas:
typeof null returns 'object' (a historical bug)

typeof can't distinguish between object subtypes (except functions)

Primitive wrapper objects ( new String() , new Number() ) have type 'object'

6. How Does this Work in JavaScript?

💡 Key Concept: The value of this is determined by how a function is called, not where it's defined
(except for arrow functions).

📋 this Resolution Rules:


Context Value of this Example

Global context Global object (or undefined in strict mode) console.log(this)

Object method The object that owns the method obj.method()

Constructor The newly created instance new Person()

Event handler The element that triggered the event button.onclick = function() {...}

Call/Apply/Bind The value explicitly provided func.call(obj)

Arrow function Lexically inherited from parent scope () => { console.log(this) }


 

🧪 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

Using regular functions instead of arrow functions in event handlers


Forgetting to bind methods in class constructors

7. What Is Function.prototype.bind and Why Is It Useful?


The bind method creates a new function with a specific this context and optional preset arguments.

javascript Copy

const john = {
age: 42,
getAge: function() {
return this.age;
},
};

console.log(john.getAge()); // 42

const unboundGetAge = john.getAge;


console.log(unboundGetAge()); // undefined

const boundGetAge = john.getAge.bind(john);


console.log(boundGetAge()); // 42

Common Uses:

Binding this : Fixing the this value for a method

Partial Application: Predefining arguments for a function

Method Borrowing: Using methods from one object on another object

8. What's the Difference Between Function Declarations and Expressions?


Function Declarations:
javascript Copy

function foo() {
console.log('Function declaration');
}

Hoisted with their body

Can be invoked before their definition

Function Expressions:

javascript Copy

const foo = function() {


console.log('Function expression');
};

Only the variable is hoisted, not the function body

Cannot be invoked before their definition

9. What Are Higher-Order Functions?


Higher-order functions either:

Take other functions as arguments


Return functions

javascript
Copy

function multiplier(factor) {
return function(number) {
return number * factor;
};
}

const double = multiplier(2);


console.log(double(5)); // 10

10. What is Lexical Scoping?


Lexical scoping determines how variable names are resolved based on their location in the code. Nested
functions have access to variables from their parent scopes.

javascript Copy

function outerFunction() {
let outerVariable = 'I am outside!';

function innerFunction() {
console.log(outerVariable); // 'I am outside!'
}

innerFunction();
}

11. What is Scope in JavaScript?


Scope defines the accessibility of variables and functions in different parts of code:

Global Scope:

Variables declared outside any function/block

Accessible throughout the entire code

Function Scope:

Variables declared within a function


Accessible only within that function

Block Scope:

Introduced in ES6 with let / const

Variables declared within a block (e.g., within {} )

Accessible only within that block


javascript Copy

// 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
}

DOM and Browser APIs

HTML Essentials

HTML5 Semantic Elements


💡 Key Concept: HTML5 introduced semantic elements that clearly describe their meaning to browsers
and developers.

Element Purpose Example Use Case

<header> Introductory content Site headers, article titles

<nav> Navigation links Main menu, pagination

<main> Main content area Primary content of the page

<article> Self-contained content Blog posts, news articles

<section> Thematic grouping Chapters, tabbed content

<aside> Tangentially related content Sidebars, call-out boxes

<footer> Footer information Copyright info, related links

<figure> Self-contained media Images with captions

<figcaption> Caption for figure Description of an image

<time> Date/time information Publication dates


 
🚀 Benefits:
Improved accessibility for screen readers

Better SEO through clearer content structure


Easier to style and maintain

More readable code

⚠️ Common Misuse:
Using <div> when a semantic element would be more appropriate

Nesting semantic elements incorrectly

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

<img src="logo.png" alt="Company


alt Alternative text for images
Logo">

aria-label Label for element without visible text <button aria-label="Close">×</button>

Links element to separate labeling


aria-labelledby <div aria-labelledby="title">...</div>
element

aria-
Links to extended description <input aria-describedby="hint">
describedby

role Explicit ARIA role for element <div role="alert">Error message</div>

tabindex Controls tab order <div tabindex="0">Interactive</div>


 

🚀 Best Practices:
Use semantic HTML elements whenever possible before resorting to ARIA

Ensure all interactive elements are keyboard accessible


Test with screen readers to verify accessibility
Maintain sufficient color contrast for text

Event delegation uses a single event listener on a parent element to manage events on its child elements,
utilizing event bubbling for efficiency.
Benefits:

Reduces memory usage by limiting the number of listeners

Dynamically handles added or removed child elements

javascript
Copy

document.getElementById('parent').addEventListener('click', (event) => {


if (event.target.tagName === 'BUTTON') {
console.log(`Clicked ${event.target.textContent}`);
}
});

13. How Do Cookies, localStorage, and sessionStorage Differ?


💡 Key Concept: Browsers offer three main mechanisms for client-side storage, each with different
limitations and use cases.

📋 Storage Comparison:
Feature Cookies localStorage sessionStorage

Capacity ~4KB ~5MB ~5MB

Expiration Manually set Never Tab close

Storage Location Browser + Server Browser only Browser only

Sent with Requests Yes No No

Accessibility Any window Any window Same tab only

APIs document.cookie localStorage API sessionStorage API


 

🛠️ Usage Examples:
javascript
Copy

// Cookies
document.cookie = "username=John; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/; Secure; SameSi

// Reading cookies requires parsing


function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}

// localStorage (persists indefinitely)


localStorage.setItem('username', 'John');
const username = localStorage.getItem('username'); // "John"
localStorage.removeItem('username');
localStorage.clear(); // Remove all items

// sessionStorage (cleared when tab closes)


sessionStorage.setItem('tempData', JSON.stringify({id: 123}));
const data = JSON.parse(sessionStorage.getItem('tempData'));

 

🚀 Best Use Cases:


Cookies: Authentication tokens, server-side session data, tracking
localStorage: User preferences, cached data, application state

sessionStorage: Form data, shopping cart, per-tab settings

⚠️ Security Considerations:
Never store sensitive information (passwords, credit cards) in client-side storage

Use HttpOnly and Secure flags for cookies with sensitive data

Set appropriate SameSite attribute on cookies (usually Strict or Lax )

Consider encrypting sensitive data if client-side storage is necessary

14. What Are <script> , <script async> , and <script defer> ?

<script> :

Blocks HTML parsing until the script loads and executes


<script async> :

Loads scripts asynchronously

Executes as soon as the script is ready

<script defer> :

Loads scripts asynchronously


Executes only after HTML parsing is complete

html
Copy

<script src="main.js"></script>
<script async src="async.js"></script>
<script defer src="defer.js"></script>

15. What is Event Bubbling?


Event bubbling occurs when an event starts at the target element and propagates up through its
ancestors.

javascript
Copy

parent.addEventListener('click', () => console.log('Parent clicked'));


child.addEventListener('click', () => console.log('Child clicked'));
// Clicking child triggers both handlers

16. What is Event Capturing?


Event capturing is when an event starts at the root and propagates down to the target element.

javascript
Copy

parent.addEventListener('click', () => console.log('Parent capturing'), true);

17. How Do mouseenter and mouseover Events Differ?


mouseenter:

Does not bubble through the DOM tree

Fires only when cursor enters the element itself


Triggers once upon entering the parent element

mouseover:

Bubbles through the DOM hierarchy


Fires when cursor enters the element or any child elements

May trigger multiple times with nested elements

18. Explain AJAX (Asynchronous JavaScript and XML)


AJAX allows web applications to send and retrieve data from a server asynchronously without page
reloads.

Key Components:

XMLHttpRequest or fetch API

Asynchronous data exchange


JSON or XML data formats
DOM manipulation to update content

fetch API Example:

javascript
Copy

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

19. How Do XMLHttpRequest and fetch() Differ?


XMLHttpRequest:

Event-based approach
More verbose syntax

Requires explicit configuration for common tasks

fetch():

Promise-based API

Cleaner, more concise syntax


Easier to chain operations

Doesn't automatically reject on HTTP error status

CSS Fundamentals

20. What is a Block Formatting Context (BFC)?


💡 Key Concept: A Block Formatting Context (BFC) is a region where the layout of block boxes occurs
and floats interact with each other.

🧱 BFC Creation Triggers:


Elements with float other than none

Elements with position: absolute or position: fixed

Elements with display: inline-block , table-cell , flex , or grid

Elements with overflow other than visible

🛠️ Practical Uses:
Containing floated elements (prevent float collapse)
Preventing margin collapsing between elements

Creating layout isolation for components


Building multi-column layouts

📝 Example:

css
Copy

.container {
/* Creates a BFC */
overflow: hidden;

/* Now this container will:


* 1. Contain all floated children
* 2. Prevent margin collapsing with other elements
* 3. Not overlap with floated siblings
*/
}
⚠️ Common Pitfalls: Using overflow: hidden to create a BFC can cut off content if it overflows the
container.

21. What is z-index and How is a Stacking Context Created?


z-index:

Controls the vertical stacking order of positioned elements

Only affects positioned elements (not static)


Higher values appear on top

Stacking Context Creation:

Root element (HTML)


Position fixed or sticky

Position absolute/relative with z-index other than auto


Elements with opacity less than 1
Elements with transform, filter, or backdrop-filter

Elements with will-change property

22. What is the Box Model in CSS?


The CSS box model describes the rectangular boxes for elements with:

Content: The actual content area


Padding: Space between content and border

Border: Line around the padding


Margin: Space outside the border

Box Sizing Options:

content-box (default): Width and height apply to content only

border-box : Width and height include content, padding, and border

23. How Do block, inline, and inline-block Display Types Differ?


Property block inline-block inline

Width Fills parent width Based on content Based on content

Height Based on content Can be specified Cannot be specified

New line Starts on new line Flows inline Flows inline

Margins/Padding All sides respected All sides respected Only horizontal sides affect layout

Examples <div> , <p> Custom buttons <span> , <a>


 

Layout and Positioning

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:

Scrolls With Creates Stacking


Position Document Flow Positioned Relative To
Page Context

static In flow N/A (normal position) Yes No

relative In flow Normal position Yes No (unless z-index)

Nearest positioned
absolute Removed Yes No (unless z-index)
ancestor

fixed Removed Viewport No Yes

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 */
}

/* Offset from normal position */


.relative {
position: relative;
top: 10px;
left: 20px;
/* Moves 10px down and 20px right from normal position */
}

/* Positioned relative to nearest positioned ancestor */


.absolute {
position: absolute;
top: 0;
right: 0;
/* Top-right corner of nearest positioned ancestor */
}

/* Positioned relative to viewport */


.fixed {
position: fixed;
bottom: 20px;
right: 20px;
/* Stays 20px from bottom-right corner of viewport */
}

/* Hybrid of relative/fixed positioning */


.sticky {
position: sticky;
top: 0;
/* Behaves like relative until page scrolls, then sticks to top */
}

⚠️ 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

sticky requires a threshold value (like top: 0 ) to work

25. When Would You Prefer translate() Over Absolute Positioning?


Use translate():

For animations and transitions (better performance)

When you want to preserve document flow


To utilize GPU acceleration
For smoother animations

Use absolute positioning:

For entirely removing elements from document flow

When precise positioning relative to a container is needed


For overlays, modals, and tooltips

26. What Does * { box-sizing: border-box; } Do?


This CSS rule applies the border-box box-sizing model to all elements, meaning:

Width and height include content, padding, and border


Makes sizing more intuitive and predictable

Simplifies responsive layouts


Prevents unexpected sizing issues when adding padding/borders

Advantages:

Easier to calculate element dimensions


More intuitive sizing behavior

Consistent with most modern CSS frameworks

Web Design Considerations

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

<html lang="en"> <!-- Base language -->


<p lang="fr">Bonjour le monde</p> <!-- Content-specific language -->

2. URL Structure Options:

Copy

domain.com/en/page (path-based)
en.domain.com/page (subdomain-based)
domain.com/page?lang=en (parameter-based)

3. Alternate Language Links:


html
Copy

<link rel="alternate" hreflang="es" href="https://domain.com/es/page">


<link rel="alternate" hreflang="x-default" href="https://domain.com/">

📱 UX & Design Considerations:


1. Text Expansion/Contraction:
German and Finnish text can be 30% longer than English
Chinese and Japanese can be 50% shorter
Design flexible layouts that accommodate text length variation

2. Reading Direction:
Support both LTR (left-to-right) and RTL (right-to-left) layouts

Use CSS dir attribute and logical properties:


css
Copy

.container {
padding-inline-start: 20px; /* Works for both LTR and RTL */
}

3. Date, Time, and Number Formats:


Use locale-aware formatting:
javascript
Copy

// US: "5/24/2023" vs. European: "24/5/2023"


new Date().toLocaleDateString('en-US');
new Date().toLocaleDateString('de-DE');

4. Cultural Considerations:
Colors have different meanings across cultures
Icons may need adaptation (e.g., mailbox designs vary globally)

Avoid text in images to facilitate translation

⚠️ Common Pitfalls:
Hard-coding strings instead of using translation files

Concatenating translated strings (breaks grammar in many languages)


Fixed-width containers that can't accommodate longer text

Forgetting to translate meta content (titles, descriptions)


Using images with embedded text

28. How Do You Utilize the CSS display Property?


Common Values:

none : Removes element from rendering

block : Full-width, starts on new line

inline : Flows with text, width based on content

inline-block : Inline flow with block properties

flex : Creates flexible container

grid : Creates grid-based layout

table , table-row , table-cell : Table-like behavior

Use Cases:

none : Hiding elements without removing from DOM

flex : Modern layout for one-dimensional content

grid : Two-dimensional layouts

inline-block : Creating horizontally aligned elements with specific dimensions


29. How Does Destructuring Assignment Work?
Destructuring extracts values from arrays or objects into individual variables.

Array Destructuring:

javascript
Copy

const [a, b, ...rest] = [1, 2, 3, 4, 5];


// a: 1, b: 2, rest: [3, 4, 5]

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' }

 

30. What is the Spread Operator and How is it Used?


The spread operator ( ... ) expands iterables into individual elements:

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

const numbers = [1, 2, 3];


Math.max(...numbers); // Same as Math.max(1, 2, 3)

31. How Do You Create Objects in JavaScript?


Object Literals:

javascript
Copy

const person = { firstName: 'John', lastName: 'Doe' };

Constructor Function:

javascript
Copy

function Person(name) {
this.name = name;
}
const john = new Person('John');

Object.create():

javascript
Copy

const proto = { greet() { console.log('Hello!'); } };


const person = Object.create(proto);
ES6 Classes:

javascript
Copy

class Person {
constructor(name) {
this.name = name;
}

greet() {
console.log(`Hello, ${this.name}!`);
}
}

32. How Does Inheritance Work in ES2015 Classes?


ES2015 classes use the extends keyword for inheritance and super to access parent methods:

javascript
Copy

class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(`${this.name} makes a noise.`);
}
}

class Dog extends Animal {


constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}

speak() {
console.log(`${this.name} barks.`); // Override parent method
}
}

33. How Does Prototypal Inheritance Work?


In JavaScript, objects inherit properties and methods from a prototype:

javascript Copy

function Animal(name) {
this.name = name;
}

Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};

function Dog(name, breed) {


Animal.call(this, name); // Call parent constructor
this.breed = breed;
}

// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// Add or override methods


Dog.prototype.speak = function() {
console.log(`${this.name} barks.`);
};

Additional Topics

34. Can You Differentiate Between Synchronous and Asynchronous Functions?


Synchronous Functions:

Execute operations sequentially, step-by-step


Block program execution until the current task completes
Follow strict line-by-line execution order

Generally easier to debug due to predictable flow


javascript
Copy

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

Non-blocking, enabling concurrent execution

Enhance performance and responsiveness

Commonly used for network requests, file I/O, timers, and animations

javascript
Copy

console.log('Start of the program');

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');

35. What Are the Pros and Cons of Using AJAX?


Advantages:

Enhanced user experience (no full page reloads)

Reduced server load (fetches only required data)


Maintains state (preserves user interactions)

Better responsiveness and interactivity

Disadvantages:

Dependency on JavaScript (breaks if disabled)

Bookmarking issues (dynamic states hard to bookmark)


SEO challenges (dynamic content harder to index)
Performance issues on low-end devices
Potential accessibility concerns

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);
}

37. What are Arrow Functions Good For?


Arrow functions ( => ) provide concise syntax and lexical this binding:

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;

// Arrow function preserves `this` from surrounding scope


setInterval(() => {
this.age++; // `this` refers to the Person instance
}, 1000);
}

38. What is Asynchronous JavaScript?


Synchronous Code:

Executes line by line

Blocks execution until current operation completes

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);
}
}

39. Explain Debouncing and Throttling


💡 Key Concept: Debouncing and throttling are performance optimization techniques that control how
many times a function is executed.

🔄 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

function debounce(func, delay) {


let timeoutId;

return function(...args) {
// Clear previous timeout
clearTimeout(timeoutId);

// Set new timeout


timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}

// Example use case: Search input


const searchInput = document.getElementById('search');
const debouncedSearch = debounce((query) => {
console.log(`Searching for: ${query}`);
fetchSearchResults(query);
}, 500);

searchInput.addEventListener('input', (e) => {


debouncedSearch(e.target.value);
});

🔄 Throttling:
Executes the function at a regular interval, regardless of how many times the event is fired

Guarantees function execution at most once per specified time period

Useful for consistent execution rates

⏱️ Throttling Implementation:
javascript
Copy

function throttle(func, limit) {


let inThrottle = false;

return function(...args) {
// If we're not throttled, execute the function
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;

// Reset throttle after specified time


setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}

// Example use case: Scroll event


const throttledScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
updateScrollIndicator(window.scrollY);
}, 300);

window.addEventListener('scroll', throttledScroll);

📊 Comparison:
Feature Debounce Throttle

Execution timing After period of inactivity At regular intervals

Usefulness When final state matters When regular updates matter

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

40. How Do Map Objects Differ from Plain Objects?


Map Objects:

Keys can be any type (objects, functions, primitives)

Maintains insertion order


Has size property

Directly iterable
Better performance for frequent additions/removals

Plain Objects:

Keys are strings or symbols


No guaranteed order (though modern engines typically preserve it)

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]'

41. What is the Difference Between .call and .apply?


Both methods invoke a function with a specific this context, but differ in how they pass arguments:

.call:

Accepts arguments as a comma-separated list


javascript Copy

function sum(a, b) {
return a + b;
}
sum.call(null, 1, 2); // 3

.apply:

Accepts arguments as an array

javascript Copy

function sum(a, b) {
return a + b;
}
sum.apply(null, [1, 2]); // 3

42. How Do null, undefined, and Undeclared Variables Differ?


null:

Explicitly represents absence of value

Type is 'object'
Must be assigned

undefined:

Variable declared but not assigned a value


Default value for function parameters, return values

Type is 'undefined'

Undeclared:

Variable not declared with var/let/const

Accessing causes ReferenceError


Not a type (it's an error condition)
javascript Copy

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:

Syntax: Classes are more readable and concise


Inheritance: Classes use extends and super for cleaner inheritance

Hoisting: Class declarations are not hoisted


Method assignment: Class methods are added to prototype automatically
Constructors: Classes use a dedicated constructor method

44. What Are the Differences Between Map/Set and WeakMap/WeakSet?


Key Differences:

Key Types:
Map/Set: Accept any value as keys

WeakMap/WeakSet: Only accept objects as keys

Memory Management:
Map/Set: Strong references prevent garbage collection

WeakMap/WeakSet: Weak references allow 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

45. How Do You Use the CSS display Property?


The display property controls how elements are rendered on the page:

block : Full width, creates a new line

inline : Flows with text, width based on content

inline-block : Inline flow with block features

flex : Creates a flexible box layout

grid : Creates a grid layout

none : Removes element from rendering

table , table-row , table-cell : Table-like behavior

Examples:
css Copy

/* Block layout */
.container { display: block; }

/* Flexible box layout */


.flex-container { display: flex; }

/* Grid layout */
.grid-container { display: grid; }

/* Hide element */
.hidden { display: none; }

46. Why Use Arrow Functions in Constructors?


Arrow functions automatically bind this to the surrounding lexical scope, which can be useful in
constructors for methods that need to preserve context:
javascript Copy

const Person = function(name) {


this.name = name;

// Regular function: 'this' context can change


this.sayName1 = function() {
console.log(this.name);
};

// Arrow function: 'this' is lexically bound to Person instance


this.sayName2 = () => {
console.log(this.name);
};
};

const john = new Person('John');


const dave = new Person('Dave');

// Regular function's 'this' can be changed


john.sayName1.call(dave); // Dave

// Arrow function's 'this' stays bound to original instance


john.sayName2.call(dave); // John

This is particularly useful in cases where methods are passed as callbacks or event handlers.

47. How Do Callback Functions Operate in Asynchronous Tasks?


Callback functions are passed as arguments to other functions and executed when an asynchronous
operation completes:
javascript Copy

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:

Enables non-blocking code execution


Follows the "continuation-passing style"

Can lead to callback hell (deeply nested callbacks)

Often replaced by Promises or async/await in modern code

48. What's the Difference Between function Person(){}, const person = Person(), and
const person = new Person()?
function Person() {}:

Declares a constructor function

Uses PascalCase by convention

Does not execute the function

const person = Person():

Calls the function as a regular function

Executes the code inside Person


Returns whatever Person returns

this inside the function refers to the global object (or undefined in strict mode)

const person = new Person():

Creates a new instance using Person as a constructor


Sets the new object's prototype to Person.prototype
Sets this to reference the new object

Executes the constructor function


Returns the new object (unless constructor returns something else)

49. What is a Practical Scenario for Using Arrow Function Syntax?


Arrow functions are especially useful for callbacks in array methods and event handlers:

Array methods:

javascript
Copy

// Traditional approach
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number) {
return number * 2;
});

// Arrow function approach


const doubled = numbers.map(number => number * 2);

Event handlers:
javascript Copy

// Traditional approach with 'this' issues


class Counter {
constructor() {
this.count = 0;
this.button = document.querySelector('#button');

// Need to bind 'this' or it will refer to the button


this.button.addEventListener('click', this.increment.bind(this));
}

increment() {
this.count++;
}
}

// Arrow function approach


class Counter {
constructor() {
this.count = 0;
this.button = document.querySelector('#button');

// Arrow function preserves 'this' from the class


this.button.addEventListener('click', () => {
this.count++;
});
}
}

50. What Does * { box-sizing: border-box; } Do?


This CSS rule applies the border-box box sizing model to all elements on the page:

Effects:

Width and height include content, padding, and border (but not margin)
Makes sizing more intuitive (add padding without changing dimensions)

Simplifies layouts (especially responsive ones)

Comparison:

Default ( content-box ): width/height = content only


border-box : width/height = content + padding + border

Advantages:

More predictable layouts

Easier to calculate dimensions

Consistent with modern CSS frameworks


Simplifies responsive design

Final Tips for Interview Success

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

⭐ During the Interview


1. Clarify questions: Ask for clarification before starting to solve a problem.

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.

⭐ Common Interview Scenarios


Scenario Strategy

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)

Framework-specific Connect answers to core JavaScript concepts

Debugging exercise Methodically isolate the issue before fixing


 
⭐ Post-Interview
1. Follow up with a thank-you note: Briefly express appreciation for the opportunity.
2. Review and learn: Note any questions you struggled with and study them.

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.

You might also like