- HTML
- CSS
- JavaScript
- Python Programming
- Java Development
- React Framework
- Angular Framework
- Node.js Backend
- SQL Databases
- MongoDB NoSQL
- Git Version Control
- Docker Containers
- AWS Cloud
- TypeScript
- Ruby on Rails
- PHP Web Development
- C# .NET
- Go Language
- Rust Programming
- Kubernetes Orchestration
Answer: HTML5 is the latest version of HyperText Markup Language used for structuring and presenting content on the World Wide Web.
Answer:
New semantic elements include <header>
, <footer>
, <article>
, <section>
, <nav>
, <aside>
, <main>
, <figure>
, <figcaption>
, <time>
, <mark>
, and <progress>
.
Answer:
The <canvas>
element is used for drawing graphics, animations, or other visual images on the fly via JavaScript.
Answer:
<div>
is a generic container for styling and scripting, while <section>
is a semantic element that represents a thematic grouping of content.
Answer:
The <article>
tag represents a self-contained composition in a document, page, or site that is independently distributable or reusable.
Answer:
The <audio>
tag is used to embed sound content in web pages.
Answer:
The <video>
tag is used to embed video content in web pages.
Answer: HTML5 introduces new elements, attributes, and APIs for multimedia, graphics, and improved semantics, while older HTML versions lack these features.
Answer:
<figure>
is used for illustrations, diagrams, photos, code listings, etc., and <figcaption>
provides a caption for the <figure>
content.
Answer:
The <nav>
element is used to define a set of navigation links.
Answer:
Use the <meta name="viewport" content="width=device-width, initial-scale=1.0">
tag and CSS media queries.
Answer:
The <header>
element represents introductory content or a set of navigational aids.
Answer:
The <footer>
element represents the footer of a section or page, typically containing copyright info, contact details, or related links.
Answer:
Data attributes (data-*
) allow you to store extra information in standard HTML elements without other hacks or non-standard attributes.
Answer:
The <progress>
element represents the completion progress of a task.
Answer:
The <meter>
element represents a scalar measurement within a known range, such as disk usage or a temperature.
Answer:
<b>
is for stylistic bold text, while <strong>
indicates importance or seriousness of the content.
Answer:
<i>
is for stylistic italic text, while <em>
indicates emphasized text.
Answer:
The <time>
element represents a specific time or date.
Answer:
The <mark>
element highlights text for reference or notation purposes.
Answer:
Use the <img src="file.svg" alt="SVG Image">
tag or inline SVG using the <svg>
element.
Answer:
The <aside>
element represents content that is tangentially related to the content around it, such as sidebars or pull quotes.
Answer: Web workers allow JavaScript to run in the background, improving performance for complex tasks.
Answer:
The <main>
element represents the dominant content of the <body>
of a document.
Answer:
The <datalist>
element provides a list of predefined options for input controls.
Answer:
The <output>
element represents the result of a calculation or user action.
Answer:
The <embed>
element is used for embedding external applications or interactive content.
Answer:
The <source>
element specifies multiple media resources for <picture>
, <audio>
, or <video>
.
Answer:
The <track>
element specifies text tracks for <audio>
or <video>
elements, such as subtitles.
Answer:
The <picture>
element allows you to specify multiple sources for an image, enabling responsive images.
Answer:
The <details>
element creates a disclosure widget, and the <summary>
element provides a summary or label for it.
Answer:
The <template>
element holds content that is not rendered when the page loads but can be instantiated later via JavaScript.
Answer:
The <wbr>
element indicates a word break opportunity—where a line break may occur if needed.
Answer:
The <keygen>
element (deprecated in HTML5.2) was used for generating cryptographic keys in web forms.
Answer:
The <dialog>
element creates a dialog box or window.
Answer:
The <menu>
element represents a list of commands or options.
Answer:
The <command>
element (deprecated) was used to define a command button.
Answer: These elements are used for ruby annotations, commonly used in East Asian typography.
Answer:
The <bdi>
element isolates a span of text that might be formatted in a different direction from other text outside it.
Answer:
The open
attribute in <details>
specifies that the details should be visible (open) by default.
Answer: It creates a date picker input field.
Answer: It creates an input field for email addresses, with built-in validation.
Answer: It creates an input field for numeric values.
Answer: It creates a slider for selecting a value from a range.
Answer: It creates a search field.
Answer: It creates an input field for telephone numbers.
Answer: It creates an input field for URLs, with built-in validation.
Answer: It creates a color picker input field.
Answer: It creates a date and time picker input field, without timezone information.
Answer:
The placeholder
attribute specifies a short hint that describes the expected value of an input field.
Answer: CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML.
Answer:
Inline (using the style
attribute), internal (using <style>
tags in the <head>
), and external (linking to a .css
file).
Answer:
id
is unique and can be used for one element; class
can be used for multiple elements.
Answer:
p { ... }
Answer:
.classname { ... }
Answer:
#idname { ... }
Answer: Content, padding, border, and margin.
Answer: Padding is space inside the border; margin is space outside the border.
Answer:
static
Answer:
static
, relative
, absolute
, fixed
, sticky
Answer:
margin: 0 auto;
Answer:
text-align: center;
Answer: Use flexbox:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
14. What is the difference between display: none and visibility: hidden?
Answer:
display: none
removes the element from the layout; visibility: hidden
hides it but keeps the space.
Answer: To wrap text around images or create multi-column layouts.
Answer:
Use clear: both;
or the clearfix hack.
Answer:
A keyword added to a selector that specifies a special state, e.g., :hover
, :active
.
Answer:
A keyword added to a selector that lets you style a specific part of an element, e.g., ::before
, ::after
.
Answer:
border: 1px solid black;
Answer:
color: red;
Answer:
background-color: blue;
Answer:
background-image: url('image.jpg');
Answer:
font-weight: bold;
Answer:
font-style: italic;
Answer:
text-decoration: underline;
Answer:
text-decoration: none;
Answer:
em
is relative to the font-size of its parent; rem
is relative to the root (html
) font-size.
Answer:
px
is an absolute unit; %
is relative to the parent element.
Answer:
font-size: 16px;
Answer:
font-family: Arial, sans-serif;
Answer: It controls the stacking order of positioned elements.
Answer: Inline elements do not start on a new line and take up only necessary width; block elements start on a new line and take up full width.
Answer:
display: block;
Answer:
display: inline;
Answer:
inline-block
allows setting width/height; inline
does not.
Answer:
It defines how the width and height of an element are calculated: content-box
or border-box
.
Answer:
content-box
Answer: It includes padding and border in the element's total width and height.
Answer:
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
}
Answer:
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
Answer:
nth-child
selects the nth child regardless of type; nth-of-type
selects the nth child of a specific type.
Answer:
:first-child
Answer:
:last-child
Answer:
tr:nth-child(odd)
Answer: It determines which CSS rule is applied when multiple rules target the same element.
Answer: By counting the number of id, class, and element selectors (id > class > element).
Answer: It overrides all other declarations, regardless of specificity.
Answer:
text-shadow: 2px 2px 4px #000;
Answer:
box-shadow: 2px 2px 4px #000;
Answer:
border-radius: 10px;
51. What is the difference between visibility: hidden and opacity: 0?
Answer:
visibility: hidden
hides the element but keeps the space; opacity: 0
makes the element fully transparent but still occupies space and is interactive.
Answer:
background-size: cover;
Answer:
background-repeat: repeat-x;
Answer: Margin is space outside the border; padding is space inside the border.
Answer:
width: 50%;
Answer:
width: 100%;
or use viewport units like vw
.
Answer: 1vw = 1% of the viewport width.
Answer: 1vh = 1% of the viewport height.
Answer:
header {
position: sticky;
top: 0;
}
Answer: Fixed is relative to the viewport and stays in place; sticky is relative to its parent until a threshold is met.
Answer:
img {
max-width: 100%;
height: auto;
}
Answer: A CSS technique to apply styles based on device characteristics, like width or orientation.
Answer:
@media (max-width: 768px) {
...;
}
Answer:
@media (max-width: 768px) {
.element {
display: none;
}
}
Answer: A layout model for arranging items in a container, allowing flexible alignment and distribution.
Answer:
display: flex;
Answer: To align items along the main axis.
Answer: To align items along the cross axis.
Answer:
It defines the direction of the main axis: row
, row-reverse
, column
, or column-reverse
.
Answer: It controls whether flex items are forced onto one line or can wrap onto multiple lines.
Answer:
align-items
sets alignment for all flex items; align-self
sets alignment for a single flex item.
Answer: A two-dimensional layout system for arranging items in rows and columns.
Answer:
display: grid;
Answer: It defines the columns in a grid layout.
Answer: It defines the rows in a grid layout.
Answer:
It defines the gap between grid items (now gap
in modern CSS).
Answer:
Use grid-column
and grid-row
.
Answer:
grid-column: span 2;
Answer: Flexbox is for one-dimensional layouts; Grid is for two-dimensional layouts.
Answer:
Use grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
Answer:
A custom property defined with --
and used with var()
.
Answer:
:root { --main-color: #333; }
Answer:
color: var(--main-color);
Answer: A way to animate changes in CSS properties over time.
Answer:
transition: property duration timing-function delay;
Answer: Transition animates property changes; animation allows for more complex, keyframe-based animations.
Answer:
@keyframes slide {
from {
transform: translateX(0);
}
to {
transform: translateX(100px);
}
}
.element {
animation: slide 2s;
}
Answer: A property to rotate, scale, skew, or translate an element.
Answer:
transform: rotate(45deg);
Answer:
transform: scale(1.5);
Answer:
transform: translate(10px, 20px);
Answer:
translate
moves the element visually without affecting layout; position
changes the element's position in the document flow.
Answer:
background: linear-gradient(to right, red, blue);
Answer:
Use viewport units: font-size: 4vw;
Answer:
min-width
sets the minimum width; max-width
sets the maximum width.
Answer: Use flexbox or grid to push the footer to the bottom of the page.
Answer:
div {
display: flex;
align-items: center;
}
or
div {
line-height: same as height;
}
Answer:
a:hover {
color: red;
}
Answer:
button:hover {
transform: scale(1.1);
}
Answer: A CSS reset removes all default browser styling; normalize.css makes styles consistent across browsers while preserving useful defaults.
Answer: JavaScript is a high-level, interpreted programming language used to create interactive and dynamic web pages.
Answer:
Primitive types: string
, number
, boolean
, null
, undefined
, bigint
, symbol
. Reference type: object
(includes arrays and functions)
Answer:
undefined
means a variable has been declared but not assigned a value. null
is an assignment value representing no value or an empty value
Answer: Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope before code execution
Answer:
var
is function-scoped, let
and const
are block-scoped. let
can be reassigned, const
cannot be reassigned
Answer:
==
checks for value equality after type coercion; ===
checks for value and type equality without coercion
Answer: A closure is a function that has access to its own scope, the outer function’s variables, and global variables
Answer: An anonymous function is a function without a name, often used as arguments to other functions
Answer: A callback is a function passed as an argument to another function and executed after some event or task
Answer: A promise is an object representing the eventual completion or failure of an asynchronous operation
Answer:
async/await
is a syntax to write asynchronous code that looks synchronous, using async
functions and the await
keyword
Answer:
setTimeout()
executes a function after a specified delay in milliseconds
Answer:
setInterval()
repeatedly executes a function at specified intervals
Answer:
Arrow functions do not have their own this
, arguments
, super
, or new.target
bindings
Answer:
this
refers to the object it belongs to, depending on how a function is called
Answer:
All three set the this
value. call()
and apply()
call the function immediately, with apply()
taking arguments as an array. bind()
returns a new function with this
set
Answer: Event bubbling is the propagation of an event from the innermost element up to the parent elements
Answer: Event capturing is the propagation of an event from the outermost element down to the target element
Answer: Event delegation is attaching a single event listener to a parent to manage events of its children
Answer:
The debugger
statement pauses code execution, allowing inspection of variables and the call stack
Answer: The Document Object Model (DOM) is a programming interface for web documents, representing the page so programs can change structure, style, and content
Answer:
document.getElementById('id')
Answer:
document.getElementsByClassName('class')
Answer:
document.getElementsByTagName('tag')
Answer:
element.addEventListener('event', function)
Answer: JSON (JavaScript Object Notation) is a lightweight data-interchange format based on JavaScript object syntax
Answer:
JSON.stringify(obj)
Answer:
JSON.parse(jsonString)
Answer: A prototype is an object from which other objects inherit properties
Answer: Prototypal inheritance is a feature where objects can inherit properties and methods from other objects
Answer:
Object.create()
creates a new object with a specified prototype; constructor functions create objects using the new
keyword
Answer:
A constructor function is used to create objects with the new
keyword
Answer: A class is a template for creating objects, introduced in ES6
Answer:
forEach()
executes a function on each element; map()
returns a new array with the results of the function
Answer:
filter()
returns all elements that match a condition; find()
returns the first element that matches
Answer:
array.includes(value)
Answer:
[...new Set(array)]
or array.filter((item, index) => array.indexOf(item) === index)
Answer:
slice()
returns a shallow copy of a portion of an array; splice()
changes the contents by removing or replacing existing elements
Answer:
push()
adds elements to the end of an array; pop()
removes the last element
Answer:
shift()
removes the first element; unshift()
adds elements to the beginning
Answer: A rest parameter allows a function to accept an indefinite number of arguments as an array
Answer:
The spread operator (...
) expands arrays or objects into individual elements
Answer: Destructuring assignment unpacks values from arrays or properties from objects into distinct variables
Answer:
Object.keys()
returns an array of keys; Object.values()
returns an array of values
Answer:
Object.freeze()
makes an object immutable; const
prevents reassignment but not mutation of the object's properties
Answer:
A generator function allows you to pause and resume execution, using the yield
keyword
Answer: Memoization is an optimization technique that stores the results of expensive function calls
Answer: Currying is converting a function with multiple arguments into a sequence of functions with single arguments
Answer: A pure function always returns the same output for the same input and has no side effects
Answer: Functional programming is a paradigm where programs are constructed by composing pure functions, avoiding shared state, mutable data, and side-effects
Note: Due to space and practical constraints, this answer provides the first 50 questions and answers in detail. However, here is a summary of additional question topics to reach 200, with brief answers or concepts. For a full list with detailed answers, consider using resources like GitHub repositories or interview prep sites
- 51. Write a function to reverse a string.
function reverse(str) {
return str.split("").reverse().join("");
}
- 52. Write a function to check if a string is a palindrome.
function isPalindrome(str) {
return str === reverse(str);
}
- 53. Write a function to find the maximum number in an array.
function max(arr) {
return Math.max(...arr);
}
- 54. Write a function to sum all numbers in an array.
function sum(arr) {
return arr.reduce((a, b) => a + b, 0);
}
- 55. Write a function to remove falsy values from an array.
function removeFalsy(arr) {
return arr.filter(Boolean);
}
- 56. Write a function to flatten a nested array.
function flatten(arr) {
return arr.flat(Infinity);
}
- 57. Write a function to count the occurrences of an element in an array.
function count(arr, val) {
return arr.filter((x) => x === val).length;
}
- 58. Write a function to implement debounce.
function debounce(fn, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
- 59. Write a function to implement throttle.
function throttle(fn, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
- 60. What is the difference between
==
andObject.is()
?Object.is()
is similar to===
but treatsNaN
as equal and differentiates+0
and-0
. - 61. How do you deep clone an object?
JSON.parse(JSON.stringify(obj));
- 62. What is the difference between
for...in
andfor...of
?for...in
iterates over enumerable property names;for...of
iterates over iterable values. - 63. What is a WeakMap? A WeakMap is a collection of key/value pairs where keys are weakly referenced.
- 64. What is a WeakSet? A WeakSet is a collection of objects where each object may occur only once.
- 65. What is a Set? A Set is a collection of unique values.
- 66. What is a Map? A Map is a collection of keyed data items, like an object but with any keys.
- 67. What is a Symbol? A Symbol is a unique and immutable primitive value, often used as object property keys.
- 68. What is the difference between
Array.isArray()
andinstanceof Array
?Array.isArray()
works across iframes;instanceof
may not. - 69. What is the difference between
Object.assign()
and the spread operator?Object.assign()
copies properties; spread operator copies enumerable own properties. - 70. What is the difference between
Array.from()
andArray.of()
?Array.from()
creates an array from an array-like or iterable object;Array.of()
creates an array from arguments. - 71. What is the difference between
parseInt()
andNumber()
?parseInt()
parses a string and returns an integer;Number()
converts a value to a number. - 72. What is the difference between
isNaN()
andNumber.isNaN()
?isNaN()
checks if a value is not a number;Number.isNaN()
checks if a value is exactlyNaN
. - 73. What is the difference between
typeof
andinstanceof
?typeof
returns a string indicating the type;instanceof
checks the prototype chain. - 74. What is the difference between
Object.getPrototypeOf()
and__proto__
?Object.getPrototypeOf()
is the standard way;__proto__
is deprecated. - 75. What is a polyfill? A polyfill is code that provides modern functionality in older browsers.
- 76. What is a shim? A shim is a library that brings a new API to an older environment.
- 77. What is a module in JavaScript? A module is a file containing JavaScript code that exports functionality.
- 78. What is CommonJS? CommonJS is a module system for JavaScript used in Node.js.
- 79. What is ES Modules? ES Modules is the official standard for modules in JavaScript.
- 80. What is a bundler? A bundler combines modules into a single file for the browser.
- 81. What is a transpiler? A transpiler converts code from one language or version to another.
- 82. What is Babel? Babel is a JavaScript compiler that transforms modern JavaScript into backwards-compatible code.
- 83. What is Webpack? Webpack is a module bundler for JavaScript applications.
- 84. What is the difference between
let
andvar
in a loop?let
is block-scoped;var
is function-scoped. - 85. What is the difference between
const
andlet
?const
cannot be reassigned;let
can. - 86. What is the difference between
null
andundefined
in type checking?typeof null
returns"object"
;typeof undefined
returns"undefined"
. - 87. What is the difference between
Array.prototype.forEach()
andArray.prototype.map()
?forEach()
does not return a new array;map()
returns a new array. - 88. What is the difference between
Array.prototype.filter()
andArray.prototype.find()
?filter()
returns all matches;find()
returns the first match. - 89. What is the difference between
Array.prototype.every()
andArray.prototype.some()
?every()
checks if all elements pass a test;some()
checks if at least one passes. - 90. What is the difference between
Array.prototype.reduce()
andArray.prototype.reduceRight()
?reduce()
processes elements left to right;reduceRight()
processes right to left. - 91. What is a higher-order function? A higher-order function takes one or more functions as arguments or returns a function.
- 92. What is a callback hell? Callback hell is a situation where callbacks are nested within callbacks, leading to unreadable code.
- 93. What is a promise chain?
A promise chain is a sequence of
.then()
calls for handling asynchronous operations. - 94. What is the difference between
Promise.all()
andPromise.race()
?Promise.all()
waits for all promises to resolve;Promise.race()
waits for the first to settle. - 95. What is async/await?
async/await
is a syntax to write asynchronous code that looks synchronous. - 96. What is the difference between
setTimeout()
andsetInterval()
?setTimeout()
executes once after a delay;setInterval()
executes repeatedly at intervals. - 97. What is the difference between
clearTimeout()
andclearInterval()
?clearTimeout()
cancels asetTimeout()
;clearInterval()
cancels asetInterval()
. - 98. What is a generator function?
A generator function can be paused and resumed, using the
yield
keyword. - 99. What is the difference between
yield
andreturn
?yield
pauses a generator function;return
ends it. - 100. What is a memoization function? A memoization function caches results of expensive function calls.
- 101. How do you handle errors in JavaScript?
Use
try...catch
blocks - 102. What is a custom error?
A custom error is an error type you define by extending
Error
. - 103. What is the difference between
throw
andreturn
?throw
raises an exception;return
exits a function with a value. - 104. What is the difference between synchronous and asynchronous code? Synchronous code runs sequentially; asynchronous code runs out of order using callbacks, promises, or async/await
- 105. What is a callback function? A function passed as an argument to another function and executed after some event or task
- 106. What is a promise chain?
A sequence of
.then()
calls for handling asynchronous operations - 107. What is the difference between
Promise.all()
andPromise.allSettled()
?Promise.all()
rejects if any promise rejects;Promise.allSettled()
waits for all to settle. - 108. What is the difference between
Promise.race()
andPromise.any()
?Promise.race()
settles when the first promise settles;Promise.any()
resolves when the first promise resolves. - 109. What is a microtask? A microtask is a task that runs after the current script and before the next event loop cycle.
- 110. What is the event loop? The event loop is a mechanism that processes events and executes callback functions
- 111. What is the difference between the call stack and the callback queue? The call stack tracks function calls; the callback queue holds functions to be executed.
- 112. What is a macro task? A macro task is a task that runs after the current script and after microtasks.
- 113. What is a debounce function? A debounce function limits the rate at which a function is called
- 114. What is a throttle function? A throttle function ensures a function is called at most once in a specified period
- 115. What is a curried function? A curried function is a function that takes multiple arguments one at a time
- 116. What is a pure function? A pure function always returns the same output for the same input and has no side effects
- 117. What is a side effect? A side effect is any application state change observable outside the called function.
- 118. What is a closure? A closure is a function that remembers its lexical scope even when executed outside that scope
- 119. What is a lexical scope? Lexical scope is the scope defined by the physical placement of variables and blocks in the source code.
- 120. What is a block scope?
Block scope is the scope of variables declared with
let
orconst
inside a block. - 121. What is a function scope?
Function scope is the scope of variables declared with
var
inside a function. - 122. What is a global scope? Global scope is the scope of variables declared outside any function or block.
- 123. What is a module scope? Module scope is the scope of variables declared in a module, not global.
- 124. What is the difference between
null
andundefined
?undefined
means a variable is declared but not assigned;null
is an assignment value - 125. What is the difference between
==
and===
?==
checks value with coercion;===
checks value and type - 126. What is the difference between
typeof
andinstanceof
?typeof
returns type as string;instanceof
checks prototype chain. - 127. What is the difference between
Object.keys()
andObject.getOwnPropertyNames()
?Object.keys()
returns enumerable properties;Object.getOwnPropertyNames()
returns all properties. - 128. What is the difference between
Object.freeze()
andObject.seal()
?Object.freeze()
makes an object immutable;Object.seal()
prevents adding or deleting properties. - 129. What is the difference between
Object.assign()
and the spread operator?Object.assign()
copies properties; spread operator copies enumerable own properties. - 130. What is the difference between
Array.from()
andArray.of()
?Array.from()
creates from array-like or iterable;Array.of()
creates from arguments. - 131. What is the difference between
isNaN()
andNumber.isNaN()
?isNaN()
checks if value is not a number;Number.isNaN()
checks if value is exactlyNaN
. - 132. What is the difference between
parseInt()
andNumber()
?parseInt()
parses string to integer;Number()
converts value to number. - 133. What is the difference between
for...in
andfor...of
?for...in
iterates over property names;for...of
iterates over values. - 134. What is the difference between
Array.prototype.forEach()
andArray.prototype.map()
?forEach()
does not return a new array;map()
returns a new array - 135. What is the difference between
Array.prototype.filter()
andArray.prototype.find()
?filter()
returns all matches;find()
returns the first match - 136. What is the difference between
Array.prototype.every()
andArray.prototype.some()
?every()
checks if all elements pass a test;some()
checks if at least one passes. - 137. What is the difference between
Array.prototype.reduce()
andArray.prototype.reduceRight()
?reduce()
processes left to right;reduceRight()
processes right to left. - 138. What is a higher-order function? A function that takes one or more functions as arguments or returns a function.
- 139. What is a callback hell? Nested callbacks leading to unreadable code
- 140. What is a promise chain?
A sequence of
.then()
calls for handling asynchronous operations - 141. What is the difference between
Promise.all()
andPromise.race()
?Promise.all()
waits for all promises to resolve;Promise.race()
waits for the first to settle. - 142. What is the difference between
Promise.all()
andPromise.allSettled()
?Promise.all()
rejects if any promise rejects;Promise.allSettled()
waits for all to settle. - 143. What is the difference between
Promise.race()
andPromise.any()
?Promise.race()
settles when the first promise settles;Promise.any()
resolves when the first promise resolves. - 144. What is the difference between
setTimeout()
andsetInterval()
?setTimeout()
executes once after a delay;setInterval()
executes repeatedly at intervals - 145. What is the difference between
clearTimeout()
andclearInterval()
?clearTimeout()
cancels asetTimeout()
;clearInterval()
cancels asetInterval()
. - 146. What is a generator function?
A generator function can be paused and resumed, using the
yield
keyword - 147. What is the difference between
yield
andreturn
?yield
pauses a generator function;return
ends it. - 148. What is a memoization function? A memoization function caches results of expensive function calls
- 149. What is a polyfill? A polyfill is code that provides modern functionality in older browsers
- 150. What is a shim? A shim is a library that brings a new API to an older environment
- 151. What is the DOM? The Document Object Model is a programming interface for web documents
- 152. How do you select an element by ID?
document.getElementById('id')
- 153. How do you select elements by class name?
document.getElementsByClassName('class')
- 154. How do you select elements by tag name?
document.getElementsByTagName('tag')
- 155. How do you select elements with CSS selectors?
document.querySelector('selector')
ordocument.querySelectorAll('selector')
- 156. How do you add an event listener?
element.addEventListener('event', function)
- 157. How do you remove an event listener?
element.removeEventListener('event', function)
- 158. What is event bubbling? Event bubbling is the propagation of an event from the innermost element up to the parent elements
- 159. What is event capturing? Event capturing is the propagation of an event from the outermost element down to the target element
- 160. What is event delegation? Event delegation is attaching a single event listener to a parent to manage events of its children
- 161. How do you prevent the default action of an event?
event.preventDefault()
- 162. How do you stop event propagation?
event.stopPropagation()
- 163. How do you create a new element?
document.createElement('tag')
- 164. How do you add a child element?
parent.appendChild(child)
- 165. How do you remove a child element?
parent.removeChild(child)
- 166. How do you get or set the text content of an element?
element.textContent
- 167. How do you get or set the inner HTML of an element?
element.innerHTML
- 168. How do you get or set the value of an input?
input.value
- 169. How do you change the style of an element?
element.style.property = value
- 170. How do you add or remove a class?
element.classList.add('class')
orelement.classList.remove('class')
- 171. How do you check if an element has a class?
element.classList.contains('class')
- 172. How do you toggle a class?
element.classList.toggle('class')
- 173. How do you get the parent of an element?
element.parentNode
- 174. How do you get the children of an element?
element.children
- 175. How do you get the next or previous sibling?
element.nextSibling
orelement.previousSibling
- 176. How do you clone an element?
element.cloneNode(true)
- 177. How do you insert an element before another?
parent.insertBefore(newNode, referenceNode)
- 178. How do you replace a child element?
parent.replaceChild(newChild, oldChild)
- 179. How do you check if an element is visible?
element.offsetParent !== null
orgetComputedStyle(element).display !== 'none'
. - 180. How do you get the position of an element?
element.getBoundingClientRect()
- 181. How do you make an AJAX request?
Use
fetch()
orXMLHttpRequest
. - 182. What is the difference between
fetch()
andXMLHttpRequest
?fetch()
is a modern, promise-based API;XMLHttpRequest
is older and callback-based. - 183. How do you send data with a POST request?
fetch(url, {
method: "POST",
body: JSON.stringify(data),
});
- 184. How do you handle JSON responses?
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data));
- 185. How do you handle errors in
fetch()
?
fetch(url)
.then((response) => {
if (!response.ok) throw Error(response.statusText);
return response.json();
})
.catch((error) => console.error(error));
- 186. What is CORS? Cross-Origin Resource Sharing is a security feature that restricts web pages from making requests to a different domain.
- 187. How do you enable CORS on the server?
Set the
Access-Control-Allow-Origin
header. - 188. What is a cookie? A cookie is a small piece of data stored on the client.
- 189. How do you set a cookie?
document.cookie = 'name=value; expires=date; path=/'
. - 190. How do you get a cookie?
document.cookie
. - 191. How do you delete a cookie? Set the cookie with an expired date.
- 192. What is localStorage?
localStorage
is a web storage API for storing data persistently in the browser. - 193. What is sessionStorage?
sessionStorage
is a web storage API for storing data for the duration of a session. - 194. How do you set an item in localStorage?
localStorage.setItem('key', 'value')
. - 195. How do you get an item from localStorage?
localStorage.getItem('key')
. - 196. How do you remove an item from localStorage?
localStorage.removeItem('key')
. - 197. How do you clear localStorage?
localStorage.clear()
. - 198. What is the difference between localStorage and sessionStorage?
localStorage
persists until cleared;sessionStorage
is cleared when the session ends. - 199. What is a module in JavaScript? A module is a file containing JavaScript code that exports functionality
- 200. How do you export and import a module?
// Export
export const name = "value";
// Import
import { name } from "./module.js";
Answer: React is an open-source JavaScript library for building user interfaces, especially single-page applications.
Answer: React was developed by Facebook.
Answer: Virtual DOM, components, JSX, one-way data binding, and declarative UI.
Answer: JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript.
Answer: Browsers only understand JavaScript, so JSX must be transpiled to JavaScript using tools like Babel.
Answer: A component is a self-contained piece of code that returns a React element to be rendered on the DOM.
Answer: Class components and Functional components.
Answer: Class components use ES6 classes and lifecycle methods; functional components are simpler, use functions, and can use hooks.
Answer: Props (short for properties) are read-only inputs passed to a component.
Answer: State is an object that stores data that may change over the lifetime of a component.
Answer: Props are passed to a component (like function parameters), while state is managed within the component (like variables declared inside a function).
Answer:
Using setState()
in class components or the state setter function from useState()
in functional components.
Answer: The Virtual DOM is a lightweight copy of the real DOM. React uses it to optimize updates and rendering.
Answer: React compares the Virtual DOM with a snapshot before and after changes to update only what has changed in the real DOM.
Answer: Keys help React identify which items have changed, are added, or are removed, improving performance.
Answer: Controlled components are form elements whose value is controlled by React state.
Answer: Uncontrolled components are form elements whose value is handled by the DOM itself, not by React state.
Answer: Hooks are functions that let you use state and other React features in functional components.
Answer:
useState
is a hook that lets you add state to functional components.
Answer:
useEffect
lets you perform side effects (like data fetching or subscriptions) in functional components.
Answer:
useRef
returns a mutable ref object whose .current
property is initialized to the passed argument.
Answer:
useContext
lets you subscribe to React context without introducing nesting.
Answer:
useReducer
is an alternative to useState
for managing complex state logic.
Answer:
useCallback
returns a memoized callback function, useful for optimizing child components that rely on reference equality.
Answer:
useMemo
returns a memoized value, useful for optimizing expensive calculations.
Answer: React context provides a way to pass data through the component tree without having to pass props down manually at every level.
Answer: A higher-order component is a function that takes a component and returns a new component with added functionality.
Answer:
Lifecycle methods are special methods in class components that allow you to run code at particular points in a component’s lifecycle (e.g., componentDidMount
).
Answer:
componentDidMount
is invoked immediately after a component is mounted (inserted into the DOM tree).
Answer:
componentDidUpdate
is invoked immediately after updating occurs (not called for the initial render).
Answer:
componentWillUnmount
is invoked immediately before a component is unmounted and destroyed.
Answer:
shouldComponentUpdate
lets you control whether a component should re-render after state or props change.
Answer: React Router is a standard library for routing in React applications.
Answer:
Using the <Route>
component, e.g., <Route path="/about" component={About} />
.
Answer:
A <Link>
is used to navigate between routes without reloading the page.
Answer:
A <NavLink>
is a special version of <Link>
that adds styling attributes when its route is active.
Answer:
A <Redirect>
is used to redirect the user to another route.
Answer:
A <Switch>
renders the first child <Route>
that matches the location.
Answer: Lazy loading is a technique for loading components only when they are needed, improving performance.
Answer:
Using React.lazy()
and Suspense
, e.g.,
const LazyComponent = React.lazy(() => import("./LazyComponent"));
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>;
Answer: Code splitting is the process of splitting your code into smaller bundles which are loaded on demand.
Answer: A React fragment lets you group a list of children without adding extra nodes to the DOM.
Answer:
Using <React.Fragment>
or the shorthand <>...</>
.
Answer: Prop drilling is the process of passing props from a parent component down through multiple layers of child components.
Answer: By using React context or state management libraries like Redux.
Answer: Redux is a predictable state container for JavaScript apps, often used with React.
Answer: Store, actions, and reducers.
Answer: The store is an object that holds the application state.
Answer: An action is an object that describes what happened in the app.
Answer: A reducer is a function that determines changes to the application’s state based on actions.
Answer:
connect
connects a React component to the Redux store.
Answer:
<Provider>
makes the Redux store available to any nested components.
Answer: Middleware provides a third-party extension point between dispatching an action and the moment it reaches the reducer (e.g., for logging, async).
Answer: Redux Thunk is middleware that allows you to write action creators that return a function instead of an action.
Answer: Redux Saga is a middleware library that helps manage side effects in Redux using ES6 generators.
Answer: Portals provide a way to render children into a DOM node that exists outside the parent component’s DOM hierarchy.
Answer:
Using ReactDOM.createPortal(child, container)
.
Answer: An error boundary is a React component that catches JavaScript errors anywhere in its child component tree.
Answer:
By defining a class component with static getDerivedStateFromError()
or componentDidCatch()
.
Answer: It renders a fallback UI after an error has been thrown.
Answer: It logs error information.
Answer:
getDerivedStateFromError
is used to render a fallback UI, and componentDidCatch
is used for side effects like logging errors.
Answer:
React.memo
is a higher-order component that memoizes the result, preventing unnecessary re-renders.
Answer:
React.memo
is for components, useMemo
is for values.
Answer:
useCallback
returns a memoized callback, useMemo
returns a memoized value.
Answer: A custom hook is a JavaScript function whose name starts with "use" and that can call other hooks.
Answer: To follow the React hooks naming convention and ensure the linter can enforce hooks rules.
Answer: SSR is rendering React components on the server and sending the HTML to the client.
Answer: Next.js is a React framework that enables server-side rendering and static site generation.
Answer: SSG is pre-rendering pages at build time and serving static HTML.
Answer: SSR generates HTML on each request; SSG generates HTML at build time.
Answer: Hydration is attaching event handlers to the server-rendered HTML to make it interactive.
Answer: React Testing Library is a lightweight solution for testing React components, focusing on behavior over implementation.
Answer: Jest is a JavaScript testing framework often used with React.
Answer: Using React Testing Library or Enzyme to render the component and assert expected behavior.
Answer: Shallow rendering renders only the component itself, not its children; deep rendering renders the component and all its children.
Answer:
propTypes
is a mechanism for type-checking props passed to a component.
Answer:
defaultProps
is a way to provide default values for props.
Answer: By using controlled components or form libraries like Formik or React Hook Form.
Answer: Formik is a library for building forms in React with ease.
Answer: React Hook Form is a library for managing forms with hooks and minimal re-renders.
Answer: Formik uses a render props pattern, React Hook Form is hook-based and optimized for performance.
Answer: A ref is a way to access DOM nodes or React elements directly.
Answer:
Using useRef
in functional components or React.createRef()
in class components.
Answer:
forwardRef
lets a component forward a ref it receives to a child component.
Answer:
The key
prop helps React identify which items have changed, are added, or are removed.
Answer: State is managed within the component; props are passed to the component from outside.
Answer: By passing a function from the parent to the child as a prop, which the child calls with data.
Answer: Reconciliation is the process by which React updates the DOM to match the most recent component tree.
Answer: React is for web development; React Native is for mobile app development.
Answer: React is a library for building UIs; Angular is a full-fledged framework.
Answer: React is a library focused on the view layer; Vue is a progressive framework.
Answer:
By using React.memo
, useMemo
, useCallback
, code splitting, lazy loading, and avoiding unnecessary re-renders.
Answer:
<StrictMode>
is a tool for highlighting potential problems in an application.
Answer:
useLayoutEffect
is similar to useEffect
, but it fires synchronously after all DOM mutations.
Answer:
useEffect
runs asynchronously after the browser has painted; useLayoutEffect
runs synchronously after DOM mutations but before painting.
Answer:
useImperativeHandle
customizes the instance value that is exposed to parent components when using ref
.
Answer:
useDebugValue
can be used to display a label for custom hooks in React DevTools.
Answer:
useReducer
is useful for managing complex state logic that involves multiple sub-values or when the next state depends on the previous one.
Answer: By using React context, Redux, or other state management libraries.
1. What is Angular and how does it differ from AngularJS?
Angular is a modern, TypeScript-based open-source framework developed by Google for building dynamic single-page applications (SPAs). Unlike AngularJS, which is based on JavaScript and uses a controller-based architecture, Angular adopts a component-based architecture, offers improved performance, better tooling (like Angular CLI), and supports mobile development[^1][^2].
2. What are the main building blocks of Angular applications?
The primary building blocks are:
- Components: Control views and logic.
- Modules: Group related components, directives, pipes, and services.
- Templates: Define the view layer.
- Services: Provide reusable business logic.
- Directives: Manipulate DOM or extend HTML.
- Pipes: Transform data in templates[^1][^2].
3. Explain the difference between Components and Directives.
- Components: Define views (UI) and logic; always have a template.
- Directives: Add behavior to existing DOM elements; do not have their own templates. Attribute directives modify the appearance/behavior of elements, while structural directives (like *ngIf, *ngFor) change the DOM layout[^1][^2].
4. What is Data Binding in Angular and what are its types?
Data binding is the mechanism to coordinate parts of a template with parts of a component. The main types are:
- Interpolation:
{{ value }}
- Property Binding:
[property]="value"
- Event Binding:
(event)="handler"
- Two-way Binding:
[(ngModel)]="value"
[^1][^2].
5. What is Angular CLI and what are some common commands?
Angular CLI is a command-line tool for creating, building, testing, and deploying Angular applications. Common commands include:
ng new
: Create a new Angular project.ng serve
: Run the development server.ng generate component|service|module
: Generate code scaffolding.ng build
: Build the application for production[^2].
6. What is RxJS and how does Angular use it?
RxJS is a library for reactive programming using Observables, allowing you to work with asynchronous data streams. Angular uses RxJS extensively for handling HTTP requests, user input events, and more, enabling powerful composition and transformation of data streams[^3].
7. What are Angular Pipes and how do you create a custom pipe?
Pipes transform displayed values in templates (e.g., date, currency). To create a custom pipe, use the @Pipe
decorator and implement the PipeTransform
interface. Example:
@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
Use in template: {{ 'hello' | capitalize }}
[^1][^2].
8. What is the difference between template-driven and reactive forms?
- Template-driven forms: Defined in the template, suitable for simple forms, use
ngModel
for two-way binding. - Reactive forms: Defined in the component class, provide more control and scalability, use
FormGroup
andFormControl
for explicit management[^2].
9. What is AOT (Ahead-of-Time) compilation and why is it important?
AOT compiles Angular HTML and TypeScript code into efficient JavaScript before the browser downloads and runs the code. This leads to faster rendering, smaller bundle sizes, and early detection of template errors[^2].
10. How does Angular prevent XSS (Cross-Site Scripting) attacks?
Angular automatically sanitizes untrusted values in templates. For example, if a <script>
tag is used within a template, Angular removes it and warns in the console, preventing script injection attacks[^4][^1]. The framework uses a built-in DOM sanitizer to ensure only safe content is rendered.
11. What are HTTP Interceptors and their use cases?
HTTP Interceptors are services that inspect and transform HTTP requests and responses globally. Use cases include adding authentication tokens, logging, error handling, and modifying request/response data[^2].
12. How does Angular support lazy loading and why is it beneficial?
Lazy loading allows modules to be loaded on demand rather than at initial load, reducing the size of the main bundle and improving application startup time. It is implemented using the Angular Router's loadChildren
property in route definitions[^1].
13. What is Angular Ivy and its advantages?
Angular Ivy is the latest rendering engine for Angular. Advantages include:
- Smaller bundle sizes.
- Faster compilation.
- Improved debugging.
- Better type checking.
- Support for lazy loading of components[^1].
14. How do you optimize Angular application performance?
- Use AOT compilation.
- Implement lazy loading.
- Use trackBy with
*ngFor
to optimize list rendering. - Avoid unnecessary change detection cycles.
- Use OnPush change detection strategy where possible.
- Minimize use of third-party libraries and large polyfills[^2].
15. What is the role of the trackBy function in ngFor?
The trackBy
function helps Angular identify items in a list by a unique identifier, reducing DOM manipulations and improving performance when rendering large lists[^2].
These questions and answers reflect the current trends and expectations for Angular interviews in 2025, covering both fundamental concepts and advanced, practical scenarios[^4][^1][^5][^3][^2].
Answer:
- The Event Loop is what allows Node.js to perform non-blocking I/O operations.
- It's a single-threaded loop that processes events and callbacks in different phases (timers, I/O callbacks, idle/prepare, poll, check, close callbacks).
- Key point: It enables Node's asynchronous nature despite JavaScript being single-threaded.
Answer:
- A fork is a remote, server-side copy of a repository, distinct from the original. A fork isn't a Git concept really, it's more a political/social idea.
- A clone is not a fork; a clone is a local copy of some remote repository. When you clone, you are actually copying the entire source repository, including all the history and branches.
- A branch is a mechanism to handle the changes within a single repository in order to eventually merge them with the rest of code. A branch is something that is within a repository. Conceptually, it represents a thread of development.