HTML, CSS, and JavaScript are fundamental skills for any aspiring web developer, and securing a job in this field can be a challenging endeavor, especially for beginners. A critical part of the interview process is the technical interview, where your proficiency in these core web technologies is thoroughly assessed. To help you prepare and boost your confidence, we’ve compiled a list of the top 50 essential interview questions and answers covering HTML, CSS, and JavaScript that are frequently asked in interviews.
Hoisting refers to JavaScript's behavior of moving variable and function declarations to the top of their scope during the compilation phase. While declarations are hoisted, initializations are not.
var
:Visualized as:
let
, const
, and class
These are hoisted but remain uninitialized, leading to a ReferenceError
if accessed before declaration.
Function declarations are fully hoisted (both declaration and definition), while function expressions are only partially hoisted (declaration without initialization).
Import statements are hoisted, making imported modules available throughout the file.
Explore the concept of "hoisting" in JavaScript on GreatFrontEnd
let
, var
, and const
Differ?var
: Function-scoped or globally scoped.let
and const
: Block-scoped, confined to their nearest enclosing block.var
and let
: Can be declared without initialization.const
: Must be initialized during declaration.var
: Allows redeclaration in the same scope.let
and const
: Redeclaration is not allowed.var
and let
: Reassignment is allowed.const
: Reassignment is not allowed.var
: Hoisted and initialized to undefined
.let
and const
: Hoisted but not initialized, causing a ReferenceError
if accessed before declaration.Explore the differences between let
, var
, and const
on GreatFrontEnd
==
and ===
?==
):===
):Prefer ===
to avoid unexpected behavior caused by type coercion, except when comparing against null
or undefined
.
Explore the difference between ==
and ===
on GreatFrontEnd
The event loop allows JavaScript to handle asynchronous tasks on a single thread, ensuring smooth execution without blocking.
setTimeout
and UI events.Promise
callbacks.Output:
Explore the event loop in JavaScript on GreatFrontEnd
Event delegation uses a single event listener on a parent element to manage events on its child elements. This approach takes advantage of event bubbling, improving efficiency.
Explore event delegation in JavaScript on GreatFrontEnd
this
Work in JavaScript?The value of this
depends on how a function is invoked:
window
in browsers).call
, apply
, or bind
.this
from the surrounding scope.Explore how this
works in JavaScript on GreatFrontEnd
localStorage
, and sessionStorage
Differ?localStorage
:sessionStorage
:Explore the difference between cookies, localStorage
, and sessionStorage
on GreatFrontEnd
<script>
, <script async>
, and <script defer>
?<script>
:<script async>
:<script defer>
:Explore the difference between <script>
, <script async>
, and <script defer>
on GreatFrontEnd
null
, undefined
, and Undeclared Variables Differ?null
:Explicitly represents no value. Use ===
to check.
undefined
:Indicates a variable has been declared but not assigned a value.
Variables not declared will throw a ReferenceError
.
Explore the difference between null
, undefined
, and undeclared variables on GreatFrontEnd
.call
and .apply
?.call
:Accepts arguments as a comma-separated list.
.apply
:Accepts arguments as an array.
Explore the difference between .call
and .apply
on GreatFrontEnd
Function.prototype.bind
and Why Is It Useful?The Function.prototype.bind
method allows you to create a new function with a specific this
context and optional preset arguments. It’s particularly useful for ensuring a function has the correct this
context when passed to another function or used as a callback.
this
: bind
is often used to fix the this
value for a method, ensuring it always refers to the intended object.bind
.bind
allows methods from one object to be used on another object.Explore Function.prototype.bind
on GreatFrontEnd
Arrow functions automatically bind the this
value to the surrounding lexical scope, which eliminates issues with context in methods. This behavior makes code more predictable and easier to debug.
this
context.Explore the advantage of using the arrow syntax for a method in a constructor on GreatFrontEnd
Prototypal inheritance allows objects to inherit properties and methods from other objects through the prototype chain.
Every JavaScript object has a prototype, which is another object from which it inherits properties.
JavaScript looks for properties and methods on the object and continues up the chain until it finds the property or reaches null
.
Used with new
to create objects and set their prototype.
Explore how prototypal inheritance works on GreatFrontEnd
function Person(){}
, const person = Person()
, and const person = new Person()
?function Person() {}
is a standard function declaration. When written in PascalCase, it conventionally represents a constructor function.
const person = Person()
calls the function and executes its code but does not create a new object.
const person = new Person()
creates a new object, setting its prototype to Person.prototype
.
Explore the differences between function declarations and expressions on GreatFrontEnd
Object()
Constructor:Object.create()
:Explore ways to create objects in JavaScript on GreatFrontEnd
Higher-order functions either:
Explore higher-order functions on GreatFrontEnd
Key Differences:
extends
and super
.Explore ES2015 classes and ES5 constructors on GreatFrontEnd
Event bubbling is when an event starts at the target element and propagates up through its ancestors.
Clicking the child triggers both handlers.
Explore event bubbling on GreatFrontEnd
Event capturing is when an event starts at the root and propagates down to the target element.
Explore event capturing on GreatFrontEnd
mouseenter
and mouseover
Events Differ in JavaScript and Browsers?mouseenter
mouseover
Example:
Example:
Understand the distinctions between synchronous and asynchronous functions on GreatFrontEnd
AJAX (Asynchronous JavaScript and XML) encompasses a collection of web development techniques that utilize various client-side technologies to build asynchronous web applications. Unlike traditional web applications where every user interaction results in a complete page reload, AJAX enables web apps to send and retrieve data from a server asynchronously. This allows for dynamic updates to specific parts of a web page without disrupting the overall page display and behavior.
Key Highlights:
XMLHttpRequest
, though fetch()
is now the preferred choice for modern web development.XMLHttpRequest
APIExample:
XMLHttpRequest
, assigns a callback to handle state changes, opens a connection to a specified URL, and sends the request.fetch()
APIExample:
.then()
to parse JSON data, and handles errors using .catch()
.fetch
fetch()
starts an asynchronous request to obtain a resource from a given URL.
Example:
fetch()
returns a Promise that resolves to a Response
object representing the server's reply.The Response
object provides methods to handle the content, such as .json()
, .text()
, and .blob()
.
Example:
fetch()
operates asynchronously, allowing the browser to perform other tasks while awaiting the server's response..then()
, .catch()
) are processed in the microtask queue as part of the event loop.fetch()
allows configuration of various request settings, including HTTP method, headers, body, credentials, and caching behavior..catch()
or try/catch
with async/await
.Learn how to explain AJAX in detail on GreatFrontEnd
AJAX (Asynchronous JavaScript and XML) facilitates the asynchronous exchange of data between web pages and servers, enabling dynamic content updates without necessitating full page reloads.
Explore the benefits and drawbacks of using AJAX on GreatFrontEnd
XMLHttpRequest
and fetch()
Differ?Both XMLHttpRequest (XHR)
and fetch()
facilitate asynchronous HTTP requests in JavaScript, but they vary in syntax, handling mechanisms, and features.
setRequestHeader
method.send
method.body
property within the options parameter is used to include the request body.responseType
property to manage different response formats.Response
object with .then
methods for accessing data.onerror
event..catch
method.abort()
method.AbortController
for canceling requests.onprogress
event.Choosing Between Them: fetch()
is generally favored for its cleaner syntax and Promise-based handling, though XMLHttpRequest
remains useful for specific scenarios like progress tracking.
Discover the distinctions between XMLHttpRequest
and fetch()
on GreatFrontEnd
JavaScript encompasses a variety of data types, which are categorized into two main groups: primitive and non-primitive (reference) types.
true
or false
.Identifying Data Types: JavaScript is dynamically typed, meaning variables can hold different types of data at various times. The typeof
operator is used to determine a variable's type.
Explore the variety of data types in JavaScript on GreatFrontEnd
Looping through object properties and array items is a fundamental task in JavaScript, and there are multiple methods to accomplish this. Below are some of the common approaches:
for...in
LoopIterates over all enumerable properties of an object, including inherited ones.
Object.keys()
Returns an array containing the object's own enumerable property names.
Object.entries()
Provides an array of the object's own enumerable string-keyed [key, value]
pairs.
Object.getOwnPropertyNames()
Returns an array of all properties (including non-enumerable ones) directly found on the object.
for
LoopA traditional loop for iterating over array elements.
Array.prototype.forEach()
Executes a provided function once for each array element.
for...of
LoopIterates over iterable objects like arrays.
Array.prototype.entries()
Provides both the index and value of each array element within a for...of
loop.
Introduced in ES2015, the spread syntax (...
) is a powerful feature for copying and merging arrays and objects without altering the originals. It's widely used in functional programming, Redux, and RxJS.
Cloning Arrays/Objects: Creates shallow copies.
Combining Arrays/Objects: Merges them into a new entity.
Passing Function Arguments: Spreads array elements as individual arguments.
Array vs. Object Spreads: Only iterables can be spread into arrays, while arrays can also be spread into objects.
The rest syntax (...
) collects multiple elements into an array or object, functioning as the opposite of spread syntax.
Function Parameters: Gathers remaining arguments into an array.
Array Destructuring: Collects remaining elements into a new array.
Object Destructuring: Gathers remaining properties into a new object.
Rest Parameter Rules: Must be the final parameter in a function.
Understand the benefits of spread syntax and how it differs from rest syntax on GreatFrontEnd
Map
Object Differ from a Plain Object in JavaScript?size
property to easily determine the number of key-value pairs.forEach
, keys()
, values()
, and entries()
.Object.keys()
, Object.values()
, or Object.entries()
to iterate.Discover the differences between a Map
object and a plain object in JavaScript on GreatFrontEnd
Map
/Set
and WeakMap
/WeakSet
?The primary distinctions between Map
/Set
and WeakMap
/WeakSet
in JavaScript are outlined below:
Key Types:
Map
and Set
accept keys of any type, including objects, primitives, and functions.WeakMap
and WeakSet
exclusively use objects as keys, disallowing primitive values like strings or numbers.Memory Management:
Map
and Set
maintain strong references to their keys and values, preventing their garbage collection.WeakMap
and WeakSet
use weak references for keys (objects), allowing garbage collection if there are no other strong references.Key Enumeration:
Map
and Set
have enumerable keys that can be iterated over.WeakMap
and WeakSet
do not allow enumeration of keys, making it impossible to retrieve lists of keys or values directly.Size Property:
Map
and Set
provide a size
property indicating the number of elements.WeakMap
and WeakSet
lack a size
property since their size can change due to garbage collection.Use Cases:
Map
and Set
are suitable for general-purpose data storage and caching.WeakMap
and WeakSet
are ideal for storing metadata or additional object-related information without preventing the objects from being garbage collected when they are no longer needed.Learn about the differences between Map
/Set
and WeakMap
/WeakSet
on GreatFrontEnd
=>
Function Syntax?One effective application of JavaScript's arrow function syntax is streamlining callback functions, especially when concise, inline function definitions are needed. Consider the following example:
Scenario: Doubling Array Elements with map
Imagine you have an array of numbers and you want to double each number using the map
method.
By utilizing arrow function syntax, the same outcome can be achieved more succinctly:
Explore a use case for the new arrow => function syntax on GreatFrontEnd
In the realm of asynchronous programming, a callback function is passed as an argument to another function and is executed once a particular task completes, such as data retrieval or handling input/output operations. Here's a straightforward explanation:
Explore the concept of a callback function in asynchronous operations on GreatFrontEnd
Debouncing and throttling are techniques used to control the rate at which functions are executed, optimizing performance and managing event-driven behaviors in JavaScript applications.
Debouncing: Delays the execution of a function until a specified period has elapsed since its last invocation. This is particularly useful for scenarios like handling search input where you want to wait until the user has finished typing before executing a function.
Throttling: Restricts a function to be executed no more than once within a given timeframe. This is beneficial for handling events that fire frequently, such as window resizing or scrolling.
These strategies help in enhancing application performance by preventing excessive function calls.
Explore the concept of debouncing and throttling on GreatFrontEnd
Destructuring assignment in JavaScript provides a concise way to extract values from arrays or properties from objects into individual variables.
This syntax employs square brackets for arrays and curly braces for objects, allowing for streamlined variable assignments directly from data structures.
Explore the concept of destructuring assignment for objects and arrays on GreatFrontEnd
Hoisting in JavaScript refers to the behavior where function declarations are moved to the top of their containing scope during the compilation phase. This allows functions to be invoked before their actual definition in the code. Conversely, function expressions and arrow functions must be defined prior to their invocation to avoid errors.
Explore the concept of hoisting with regards to functions on GreatFrontEnd
In ES2015, JavaScript introduces the class
syntax with the extends
keyword, enabling one class to inherit properties and methods from another. The super
keyword is used to access the parent class's constructor and methods.
In this example, the Dog
class inherits from the Animal
class, demonstrating how classes facilitate inheritance and method overriding in JavaScript.
Explore the concept of inheritance in ES2015 classes on GreatFrontEnd
Lexical scoping in JavaScript determines how variable names are resolved based on their location within the source code. Nested functions have access to variables from their parent scopes, enabling them to utilize and manipulate these variables.
In this scenario, innerFunction
can access outerVariable
because of lexical scoping rules, which allow inner functions to access variables defined in their outer scope.
Explore the concept of lexical scoping on GreatFrontEnd
Scope in JavaScript defines the accessibility of variables and functions in different parts of the code. There are three primary types of scope:
let
or const
within a block (e.g., within {}
) are accessible only within that block.In this example, globalVar
is accessible globally, functionVar
is confined to myFunction
, and blockVar
is restricted to the if
block.
Explore the concept of scope in JavaScript on GreatFrontEnd
The spread operator (...
) in JavaScript allows iterable elements (like arrays or objects) to be expanded into individual elements. It's versatile and can be used for copying, merging, and passing array elements as function arguments.
The spread operator simplifies operations such as copying arrays or objects, merging multiple arrays or objects into one, and spreading elements of an array as individual arguments to functions.
Explore the concept of the spread operator and its uses on GreatFrontEnd
this
Binding Work in Event Handlers?In JavaScript, the this
keyword refers to the object that is executing the current piece of code. Within event handlers, this
typically points to the DOM element that triggered the event. However, its value can change depending on how the handler is defined and invoked. To ensure this
references the intended context, techniques like using bind()
, arrow functions, or explicitly setting the context are employed.
These methods help maintain the correct reference for this
within event handling functions, ensuring consistent and predictable behavior across various event-driven scenarios in JavaScript applications.
Explore the concept of this
binding in event handlers on GreatFrontEnd
A Block Formatting Context (BFC) is a pivotal concept in CSS that influences how block-level elements are rendered and interact on a webpage. It creates an isolated environment where block boxes are laid out, ensuring that elements like floats, absolutely positioned elements, inline-blocks
, table-cells
, table-captions
, and those with an overflow
value other than visible
(except when propagated to the viewport) establish a new BFC.
Grasping how to initiate a BFC is essential because, without it, the containing box might fail to encompass floated child elements. This issue is akin to collapsing margins but is often more deceptive, causing entire boxes to collapse unexpectedly.
A BFC is formed when an HTML box satisfies at least one of the following criteria:
float
property is set to a value other than none
.position
property is assigned a value that is neither static
nor relative
.display
property is set to table-cell
, table-caption
, inline-block
, flex
, inline-flex
, grid
, or inline-grid
.overflow
property is set to a value other than visible
.Within a BFC, each box's left outer edge aligns with the left edge of its containing block (or the right edge in right-to-left layouts). Additionally, vertical margins between adjacent block-level boxes within a BFC collapse into a single margin.
Discover Block Formatting Context (BFC) and its Operation on GreatFrontEnd
z-index
and How is a Stacking Context Created?The z-index
property in CSS manages the vertical stacking order of overlapping elements. It only influences positioned elements—those with a position
value other than static
—and their descendants or flex items.
In the absence of a z-index
value, elements stack based on their order in the Document Object Model (DOM), with elements appearing later in the HTML markup rendered on top of earlier ones at the same hierarchy level. Positioned elements (those with non-static positioning) and their children will always overlay elements with default static positioning, regardless of their order in the HTML structure.
A stacking context is essentially a group of elements that share a common stacking order. Within a local stacking context, the z-index
values of child elements are relative to that context rather than the entire document. Elements outside of this context—such as sibling elements of a local stacking context—cannot interpose between layers within it. For instance, if element B overlays element A, a child of element A, element C, cannot surpass element B in the stacking order even if it has a higher z-index
than element B.
Each stacking context operates independently; after stacking its child elements, the entire context is treated as a single entity within the parent stacking context's order. Certain CSS properties, like an opacity
less than 1, a filter
that isn't none
, or a transform
that isn't none
, can trigger the creation of a new stacking context.
Learn about z-index
and Stacking Contexts on GreatFrontEnd
This topic relates to writing efficient CSS, specifically how browsers interpret and apply CSS selectors. Browsers process selectors from right to left, starting with the most specific (the key selector) and moving outward. They first identify all elements that match the rightmost part of the selector and then traverse up the DOM tree to verify if those elements meet the remaining parts of the selector.
For example, consider the selector p span
. Browsers will first locate all <span>
elements and then check each span's ancestor chain to determine if it is within a <p>
element. Once a <p>
ancestor is found for a given <span>
, the browser confirms that the <span>
matches the selector and ceases further traversal for that element.
The efficiency of selector matching is influenced by the length of the selector chain—the shorter the chain, the quicker the browser can verify matches.
Understand How Browsers Match CSS Selectors on GreatFrontEnd
The CSS box model is a fundamental concept that describes the rectangular boxes generated for elements in the document tree, determining how they are laid out and displayed. Each box comprises a content area (such as text or images) surrounded by optional padding
, border
, and margin
areas.
The box model is responsible for calculating:
width
, height
, padding
, and border
.height
is specified, a block element's height adjusts to its content plus padding
(unless floats are involved).width
is set, a non-floated block element expands to fit its parent's width minus padding
, unless a max-width
is specified.
table
, figure
, and input
have inherent width values and may not expand fully.span
do not have a default width and will not expand to fit.height
and width
are determined by its content.box-sizing: content-box
), padding
and border
are not included in an element's width
and height
.Note: Margins do not contribute to the actual size of the box; they affect the space outside the box. The box's area is confined to the border
and does not extend into the margin
.
Understanding the box-sizing
property is crucial as it alters how an element's height
and width
are calculated.
box-sizing: content-box
: The default behavior where only the content size is considered.box-sizing: border-box
: Includes padding
and border
in the element's total width
and height
, excluding margin
.Many CSS frameworks adopt box-sizing: border-box
globally for a more intuitive sizing approach.
Explore the Box Model and Its Control in CSS on GreatFrontEnd
display
Property? Provide Examples.The display
property in CSS dictates how an element is rendered in the document flow. Common values include none
, block
, inline
, inline-block
, flex
, grid
, table
, table-row
, table-cell
, and list-item
.
Description:
none
Hides the element; it does not occupy any space in the layout. All child elements are also hidden. The element is treated as if it does not exist in the DOM.
block
The element occupies the full width available, starting on a new line.
inline
The element does not start on a new line and only occupies as much width as necessary.
inline-block
Combines characteristics of both inline
and block
. The element flows with text but can have width
and height
set.
flex
Defines the element as a flex container, enabling the use of flexbox layout for its children.
grid
Defines the element as a grid container, allowing for grid-based layout of its children.
table
Makes the element behave like a <table>
element.
table-row
Makes the element behave like a <tr>
(table row) element.
table-cell
Makes the element behave like a <td>
(table cell) element.
list-item
Makes the element behave like a <li>
(list item) element, enabling list-specific styling such as list-style-type
and list-style-position
.
For a comprehensive list of display
property values, refer to the CSS Display | MDN.
Understand the CSS display
Property with Examples on GreatFrontEnd
relative
, fixed
, absolute
, sticky
, and static
Positioning Differ?In CSS, an element's positioning is determined by its position
property, which can be set to relative
, fixed
, absolute
, sticky
, or static
. Here's how each behaves:
static
: The default positioning. Elements flow naturally within the document. The top
, right
, bottom
, left
, and z-index
properties have no effect.
relative
: The element is positioned relative to its normal position. Adjustments using top
, right
, bottom
, or left
move the element without affecting the layout of surrounding elements, leaving a gap where it would have been.
absolute
: The element is removed from the normal document flow and positioned relative to its nearest positioned ancestor (an ancestor with a position
other than static
). If no such ancestor exists, it positions relative to the initial containing block. Absolutely positioned elements do not affect the position of other elements and can have width
and height
specified.
fixed
: Similar to absolute
, but the element is positioned relative to the viewport, meaning it stays in the same place even when the page is scrolled.
sticky
: A hybrid of relative
and fixed
. The element behaves like relative
until it crosses a specified threshold (e.g., scroll position), after which it behaves like fixed
, sticking to its position within its parent container.
Understanding these positioning schemes is vital for controlling the layout and behavior of elements, especially in responsive and dynamic designs.
Learn About Positioning Schemes in CSS on GreatFrontEnd
Designing and developing for multilingual websites involves various considerations to ensure accessibility and usability across different languages and cultures. This process is part of internationalization (i18n).
lang
attribute on the <html>
tag to specify the page's language.en_US
, zh_CN
).<link rel="alternate" hreflang="other_locale" href="url_for_other_locale">
to inform search engines about alternate language versions of the page.<link rel="alternate" href="url_for_fallback" hreflang="x-default" />
.en-US
vs. en-GB
, zh-CN
vs. zh-TW
).Accept-Language
headers and IP addresses.Dynamic Content: Instead of concatenating strings (e.g., "The date today is " + date
), use template strings with parameter substitution to accommodate different grammar structures across languages.
Example:
Understand Multilingual Design Considerations on GreatFrontEnd
block
, inline
, and inline-block
Display Types Differ?The display
property in CSS determines how elements are rendered on the page. The block
, inline
, and inline-block
values have distinct behaviors and use cases:
Property | block | inline-block | inline |
---|---|---|---|
Size | Fills up the width of its parent container. | Depends on content. | Depends on content. |
Positioning | Start on a new line and tolerates no HTML elements next to it (except when you add float ) | Flows along with other content and allows other elements beside it. | Flows along with other content and allows other elements beside it. |
Can specify width and height | Yes | Yes | No. Will ignore if being set. |
Can be aligned with vertical-align | No | Yes | Yes |
Margins and paddings | All sides respected. | All sides respected. | Only horizontal sides respected. Vertical sides, if specified, do not affect layout. Vertical space it takes up depends on line-height , even though the border and padding appear visually around the content. |
Float | - | - | Becomes like a block element where you can set vertical margins and paddings. |
Use Cases | Layout elements like <div> , <p> , <section> . | Used for buttons, images, and form fields that need custom sizes but stay in line with text. | Links <a> , text formatting <span> , text styling - bold <b> , italics <i> . |
Learn the Differences Between block
, inline
, and inline-block
on GreatFrontEnd
translate()
Over Absolute Positioning, or Vice Versa?The translate()
function is a part of the CSS transform
property and offers a different approach to positioning compared to absolute
positioning. Here's why you might choose one over the other:
Using translate()
:
position: relative
.transform
or opacity
does not trigger browser reflows or repaints; instead, it initiates a composition layer. This results in smoother and more efficient animations, as translate()
leverages the GPU for rendering.Using absolute
Positioning:
Why Choose translate()
?
For animations and dynamic movements where performance and smoothness are critical, translate()
is more efficient. It avoids the costly reflows associated with changing layout-affecting properties like top
and left
.
Why Choose absolute
Positioning?
When you need to position elements precisely without regard to their original place in the document flow, absolute
positioning is the way to go. It's essential for creating overlays, modals, and tooltips that need to appear in specific locations on the screen.
Understand When to Use translate()
vs. Absolute Positioning on GreatFrontEnd
* { box-sizing: border-box; }
Do and What Are Its Advantages?Applying * { box-sizing: border-box; }
in your CSS ensures that all elements on the page use the border-box
model for calculating their width
and height
.
By default, elements use box-sizing: content-box
, where the width
and height
only account for the content area. When you set box-sizing: border-box
, the width
and height
properties include the element's padding
and border
, but not the margin
.
Property | box-sizing: content-box (default) | box-sizing: border-box |
---|---|---|
content | Yes | Yes |
padding | No | Yes |
border | No | Yes |
margin | No | No |
padding
and border
within the width
and height
makes it easier to calculate the size of elements, aligning more closely with designers' expectations.padding
or border
to elements, as it doesn't alter the total size.box-sizing: border-box
globally to maintain consistency and predictability in element sizing.Explore What * { box-sizing: border-box; }
Does and Its Benefits on GreatFrontEnd
Congratulations on reaching the end of our comprehensive collection of HTML, CSS, and JavaScript interview questions and answers! We hope this resource has equipped you with the confidence and skills needed to excel in your upcoming interviews. Remember, consistent practice is essential, so keep coding and revisiting these concepts until they become second nature.