JavaScript Concepts Explained
JavaScript Concepts Explained
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.
[Link](foo); // undefined
var foo = 1;
[Link](foo); // 1
Visualized as:
var foo;
[Link](foo); // undefined
foo = 1;
[Link](foo); // 1
These are hoisted but remain uninitialized, leading to a ReferenceError if accessed before
declaration.
[Link](bar); // ReferenceError
Function declarations are fully hoisted (both declaration and definition), while function
expressions are only partially hoisted (declaration without initialization).
[Link](declared()); // Works
function declared() {
[Link](expr); // undefined
};
Imports
Import statements are hoisted, making imported modules available throughout the file.
[Link](); // Accessible
1. Scope:
function test() {
var a = 1;
let b = 2;
const c = 3;
[Link](a); // ReferenceError
[Link](b); // ReferenceError
[Link](c); // ReferenceError
2. Initialization:
var a;
let b;
3. Redeclaration:
• var**: Allows redeclaration in the same scope.
var x = 1;
var x = 2; // Valid
let y = 1;
let y = 2; // SyntaxError
4. Reassignment:
const z = 1;
z = 2; // TypeError
5. Hoisting:
• let and const**: Hoisted but not initialized, causing a ReferenceError if accessed before
declaration.
[Link](a); // undefined
var a = 1;
[Link](b); // ReferenceError
let b = 2;
42 == '42'; // true
0 == false; // true
Best Practice:
Prefer === to avoid unexpected behavior caused by type coercion, except when comparing
against null or undefined.
The event loop allows JavaScript to handle asynchronous tasks on a single thread, ensuring
smooth execution without blocking.
Components:
2. Web APIs: Handle asynchronous tasks like timers and HTTP requests.
Execution Order:
[Link]('Start');
setTimeout(() => [Link]('Timeout'), 0);
[Link]('End');
Output:
Start
End
Promise
Timeout
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.
[Link](`Clicked ${[Link]}`);
});
const obj = {
name: 'Alice',
greet() {
[Link]([Link]);
},
};
[Link](); // Alice
Cookies:
[Link]([Link]);
localStorage:
[Link]('key', 'value');
[Link]([Link]('key'));
sessionStorage:
• Limited to 5MB.
[Link]('key', 'value');
[Link]([Link]('key'));
<script async>:
• Executes as soon as the script is ready, potentially before HTML parsing completes.
<script defer>:
<script src="[Link]"></script>
null:
undefined:
Undeclared:
let a;
[Link](a); // undefined
let b = null;
[Link](b); // null
.call:
function sum(a, b) {
return a + b;
[Link]([Link](null, 1, 2)); // 3
const john = {
age: 42,
getAge: function () {
return [Link];
},
};
[Link]([Link]()); // 42
[Link](unboundGetAge()); // undefined
[Link](boundGetAge()); // 42
[Link](boundGetAgeMary()); // 21
Common Uses:
1. **Binding this: bind is often used to fix the this value for a method, ensuring it always
refers to the intended object.
2. Partial Application: You can predefine some arguments for a function using bind.
3. Method Borrowing: bind allows methods from one object to be used on another
object.
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.
[Link] = name;
this.sayName1 = function () {
[Link]([Link]);
};
this.sayName2 = () => {
[Link]([Link]);
};
};
john.sayName2(); // John
[Link](dave); // Dave
[Link](dave); // John
When to Use:
• In scenarios like React class components, where methods are passed as props and
need to retain their original this context.
Prototypal inheritance allows objects to inherit properties and methods from other objects
through the prototype chain.
Key Concepts:
1. Prototypes:
Every JavaScript object has a prototype, which is another object from which it inherits
properties.
[Link] = name;
[Link] = age;
[Link] = function () {
};
2. Prototype Chain:
JavaScript looks for properties and methods on the object and continues up the chain until it
finds the property or reaches null.
3. Constructor Functions:
function Animal(name) {
[Link] = name;
[Link] = function () {
};
[Link](this, name);
[Link] = breed;
[Link] = [Link]([Link]);
[Link] = function () {
[Link]('Woof!');
};
[Link](); // Woof!
14. What’s the Difference Between function Person(){}, const person = Person(), and const
person = new Person()?
Function Declaration:
Function Call:
const person = Person() calls the function and executes its code but does not create a new
object.
Constructor Call:
const person = new Person() creates a new object, setting its prototype to [Link].
Function Declarations:
function foo() {
[Link]('Function declaration');
Function Expressions:
[Link]('Function expression');
};
1. Object Literals:
2. Object() Constructor**:
[Link] = 'John';
[Link] = 'Doe';
3. [Link]()**:
const proto = {
greet() {
[Link]('Hello!');
},
};
[Link](); // Hello!
4. ES2015 Classes:
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
2. Return functions.
function multiplier(factor) {
};
}
const double = multiplier(2);
[Link](double(5)); // 10
ES5 Constructor:
function Person(name) {
[Link] = name;
[Link] = function () {
};
ES2015 Class:
class Person {
constructor(name) {
[Link] = name;
greet() {
Key Differences:
Event bubbling is when an event starts at the target element and propagates up through its
ancestors.
[Link]('click', () => [Link]('Parent clicked'));
Event capturing is when an event starts at the root and propagates down to the target
element.
Enabling Capturing:
21. How Do the mouseenter and mouseover Events Differ in JavaScript and Browsers?
mouseenter
• Fires solely when the cursor enters the element itself, excluding its child elements
• Triggers only once upon entering the parent element, regardless of its internal content
mouseover
• Activates when the cursor enters the element or any of its descendant elements
• May lead to multiple event callbacks if there are nested child elements
Synchronous Functions
• Are generally easier to comprehend and debug due to their predictable flow
• Common use cases include reading files synchronously and iterating over large
datasets
Example:
const fs = require('fs');
Asynchronous Functions
• Allow the program to continue running without waiting for the task to finish
• Enable other operations to proceed while waiting for responses or the completion of
time-consuming tasks
• Commonly used for network requests, file I/O, timers, and animations
Example:
fetch('[Link]
[Link]('End of program');
Key Highlights:
• Data Formats: Initially utilized XML, but JSON has become more prevalent due to its
seamless compatibility with JavaScript.
XMLHttpRequest API
Example:
[Link] = function () {
[Link]([Link]);
} else {
};
[Link]();
fetch() API
Example:
fetch('[Link]
.then((response) => {
if (![Link]) {
return [Link]();
})
• Process: Starts a fetch request, processes the response with .then() to parse JSON data,
and handles errors using .catch().
1. Initiating a Request
• Example:
fetch('[Link] {
headers: {
'Content-Type': 'application/json',
},
});
2. Promise-Based Response
• 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('[Link]
4. Asynchronous Nature
• fetch()** operates asynchronously, allowing the browser to perform other tasks while
awaiting the server's response.
• Promises (.then(), .catch()) are processed in the microtask queue as part of the event
loop.
6. Handling Errors
• Errors such as network failures or invalid responses are captured and managed
through the Promise chain using .catch() or try/catch with async/await**.
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.
Advantages
• Enhanced User Experience: Updates content seamlessly without refreshing the entire
page.
• Improved Performance: Reduces server load by fetching only the required data.
• Maintains State: Preserves user interactions and client-side states within the page.
Disadvantages
• SEO Challenges: Search engines may find it hard to index dynamically loaded content
effectively.
Both XMLHttpRequest (XHR) and fetch() facilitate asynchronous HTTP requests in JavaScript,
but they vary in syntax, handling mechanisms, and features.
• fetch(): The body property within the options parameter is used to include the request
body.
Handling Responses
• fetch(): Offers a unified Response object with .then methods for accessing data.
Managing Errors
Canceling Requests
Tracking Progress
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.
JavaScript encompasses a variety of data types, which are categorized into two main groups:
primitive and non-primitive (reference) types.
• Undefined: A variable that has been declared but not assigned a value.
• Symbol: A unique and immutable value used primarily as object property keys.
• BigInt: Allows representation of integers with arbitrary precision, useful for very large
numbers.
• Function: Functions are treated as objects and can be defined using declarations or
expressions.
• RegExp: Used for defining regular expressions for pattern matching within strings.
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.
27. What Constructs Do You Use to Iterate Over Object Properties and Array Elements?
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:
1. for...in Loop
if ([Link](obj, property)) {
[Link](property);
2. [Link]()
3. [Link]()
Provides an array of the object's own enumerable string-keyed [key, value] pairs.
4. [Link]()
Returns an array of all properties (including non-enumerable ones) directly found on the
object.
1. for Loop
[Link](arr[i]);
2. [Link]()
3. for...of Loop
[Link](element);
4. [Link]()
Provides both the index and value of each array element within a for...of loop.
28. What Are the Advantages of Using Spread Syntax, and How Does It Differ from Rest
Syntax?
Spread Syntax
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.
const newObj = { ...obj, city: 'New York' }; // { name: 'John', age: 30, city: 'New York' }
• Array vs. Object Spreads: Only iterables can be spread into arrays, while arrays can
also be spread into objects.
Rest Syntax
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.
function addFiveToNumbers(...numbers) {
const { e, f, ...others } = { e: 1, f: 2, g: 3, h: 4 };
// e: 1, f: 2, others: { g: 3, h: 4 }
29. How Does a Map Object Differ from a Plain Object in JavaScript?
Map Object
• Key Flexibility: Allows keys of any type, including objects, functions, and primitives.
• Size Property: Includes a size property to easily determine the number of key-value
pairs.
• Iteration: Directly iterable with methods like forEach, keys(), values(), and entries().
• Performance: Typically offers better performance for larger datasets and frequent
modifications.
Plain Object
• Key Types: Primarily uses strings or symbols as keys. Non-string keys are converted to
strings.
• Order: Does not guarantee the order of key insertion.
• Size Tracking: Lacks a built-in property to determine the number of keys; requires
manual counting.
// Map
[Link]('key1', 'value1');
[Link]([Link]); // 2
// Plain Object
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.
• 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.
• 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.
31. What is a Practical Scenario for Using the Arrow => Function Syntax?
Imagine you have an array of numbers and you want to double each number using
the map method.
return number * 2;
});
[Link](doubledNumbers); // Output: [2, 4, 6, 8, 10]
By utilizing arrow function syntax, the same outcome can be achieved more succinctly:
function fetchData(callback) {
setTimeout(() => {
callback(data);
}, 1000);
fetchData((data) => {
});
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.
let timeoutId;
clearTimeout(timeoutId);
};
let inThrottle;
if (!inThrottle) {
[Link](this, args);
inThrottle = true;
};
34. How Does Destructuring Assignment Work for Objects and Arrays?
Destructuring assignment in JavaScript provides a concise way to extract values from arrays or
properties from objects into individual variables.
// Array destructuring
// Object destructuring
This syntax employs square brackets for arrays and curly braces for objects, allowing for
streamlined variable assignments directly from data structures.
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.
// Function declaration
function hoistedFunction() {
// Function expression
};
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.
class Animal {
constructor(name) {
[Link] = name;
speak() {
constructor(name, breed) {
super(name);
[Link] = breed;
speak() {
[Link](`${[Link]} barks.`);
In this example, the Dog class inherits from the Animal class, demonstrating how classes
facilitate inheritance and method overriding in JavaScript.
function outerFunction() {
function innerFunction() {
innerFunction();
outerFunction();
In this scenario, innerFunction can access outerVariable because of lexical scoping rules,
which allow inner functions to access variables defined in their outer scope.
Scope in JavaScript defines the accessibility of variables and functions in different parts of the
code. There are three primary types of scope:
1. Global Scope: Variables declared outside any function or block are accessible
throughout the entire code.
2. Function Scope: Variables declared within a function are accessible only within that
function.
3. Block Scope: Introduced in ES6, variables declared with let or const within a block
(e.g., within {}) are accessible only within that block.
// Global scope
// Function scope
if (true) {
// Block scope
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.
// Copying an array
// Merging arrays
// Copying an object
const obj1 = { a: 1, b: 2 };
// Merging objects
const obj3 = { c: 3, d: 4 };
[Link](sum(...numbers)); // Output: 6
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.
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.
41. What is a Block Formatting Context (BFC) and How Does It Function?
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:
• The position property is assigned a value that is neither static nor relative.
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.
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.
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.
44. What is the Box Model in CSS and How Can You Control Its Rendering?
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.
• Automatic Width: If no width is set, a non-floated block element expands to fit its
parent's width minus padding, unless a max-width is specified.
• Certain block-level elements like table, figure, and input have inherent width
values and may not expand fully.
• Inline elements like span do not have a default width and will not expand to fit.
• Content Dimensions: An element's height and width are determined by its content.
• Box-Sizing: By default (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.
Additional Considerations
• box-sizing: content-box:** The default behavior where only the content size is
considered.
Many CSS frameworks adopt box-sizing: border-box globally for a more intuitive sizing
approach.
45. How Do You Utilize the CSS 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
table-row
table-cell
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.
46. How Do 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.
• 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.
47. What Should You Consider When Designing for Multilingual Websites?
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).
• Language Attribute: Use the lang attribute on the <html> tag to specify the page's
language.
• Fallback Pages: Provide a fallback page for unmatched languages using <link
rel="alternate" href="url_for_fallback" hreflang="x-default" />.
• Locale: Controls regional settings like number formats, dates, and times, which may
vary within a language.
• Language Variations: Recognize that widely spoken languages have different dialects
and regional variations (e.g., en-US vs. en-GB, zh-CN vs. zh-TW).
• Automatic Detection: Servers can detect a visitor's locale using HTTP Accept-
Language headers and IP addresses.
• User Control: Allow users to easily change their preferred language and locale settings
to account for inaccuracies in automatic detection.
Text Length and Layout
• Variable Lengths: Be aware that translations can alter text length, potentially affecting
layout and causing overflow issues.
• Design Flexibility: Avoid rigid designs that cannot accommodate varying text lengths,
especially for headings, labels, and buttons.
Reading Direction
• Left-to-Right (LTR) vs. Right-to-Left (RTL): Accommodate different text directions, such
as Hebrew and Arabic, by designing flexible layouts that can adapt to both LTR and RTL
orientations.
• 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:
// English
// Chinese
• Regional Formats: Adapt date and currency formats to match regional conventions
(e.g., "May 31, 2012" in the U.S. vs. "31 May 2012" in Europe).
Text in Images
• Color Sensitivity: Be mindful that colors can carry different meanings and emotions
across cultures. Choose color schemes that are culturally appropriate and inclusive.
inline-
Property block block inline
Flows
along
with
other
content
Start on a new line and
and tolerates no allows
HTML elements other Flows along with other
next to it (except element content and allows
when you s beside other elements beside
Positioning add float) it. it.
Can
specify width and No. Will ignore if being
height Yes Yes set.
Can be aligned
with vertical-align No Yes Yes
Becomes like
a block element where
you can set vertical
Float - - margins and paddings.
Used for
buttons,
images,
and
form
fields
that
need
custom
sizes but Links <a>, text
Layout elements stay in formatting <span>, text
like <div>, <p>, <se line with styling - bold <b>,
Use Cases ction>. text. italics <i>.
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:
49. When Would You Prefer 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():
.element {
transform: translateX(50px);
• Flow Removal: The element is taken out of the normal document flow, and its
position is calculated relative to the nearest positioned ancestor or the
viewport.
• Reflow Trigger: Changing an element's absolute position can cause the browser
to recalculate the layout (reflow), which is more CPU-intensive.
.element {
position: absolute;
top: 20px;
left: 30px;
}
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.
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.
50. What Does * { 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.
What It Does
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.
Comparison Table
padding No Yes
border No Yes
margin No No
Advantages
• Intuitive Sizing: Including padding and border within the width and height makes it
easier to calculate the size of elements, aligning more closely with designers'
expectations.
• Consistency Across Frameworks: Many CSS frameworks like Bootstrap, Tailwind, and
Bulma set box-sizing: border-box globally to maintain consistency and predictability in
element sizing.