Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.
JavaScript Tutorial · JavaScript
Short answer: JavaScript is essential when working with JavaScript Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
JavaScript Tutorial · Components
Short answer: Components is essential when working with JavaScript Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
JavaScript Tutorial · State
Short answer: State is essential when working with JavaScript Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
JavaScript Tutorial · API integration
Short answer: API integration is essential when working with JavaScript Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
JavaScript Tutorial · Performance
Short answer: Performance is essential when working with JavaScript Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
HTML5 is the modern evolution of HTML4, introducing better structure, multimedia support,
and APIs.
Follow me on LinkedIn:
HTML4 mainly focused on document markup, while HTML5 focuses on building interactive
web applications.
Key differences:
Feature HTML4 HTML5
Doctype Long and complex Simple <!DOCTYPE html>
Multimedia Needs Flash Native <audio> and <video>
Semantics Limited New tags: <header>, <footer>,
<article>, <nav>
Storage Cookies localStorage, sessionStorage
Forms Basic New input types: email, date, number
Example:
<!DOCTYPE html>
<html>
<body>
<header>
<h1>HTML5 Example</h1>
</header>
</body>
</html>
Key Takeaway:
HTML5 = Simpler, smarter, and built for modern web apps.
JavaScript JavaScript Tutorial · JavaScript
A closure is created when a function remembers variables from its outer scope, even
after that outer function has finished executing.
Example:
function makeCounter() {
let count = 0;
return function() {
return ++count;
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
✅ Use cases: data privacy, memoization, and function factories.
JavaScript JavaScript Tutorial · JavaScript
A higher-order function is a function that takes another function as an argument or
returns a function.
They are key to functional programming in JavaScript.
Example:
function greet(name) {
return `Hello, ${name}`;
Follow me on LinkedIn:
function processUser(callback) {
return callback("Alice");
console.log(processUser(greet)); // Hello, Alice
Functions like map(), filter(), and reduce() are higher-order functions.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
They are part of the browser’s rendering process when the DOM or styles change.
changing size, position, or adding elements).
→ Expensive operation since it recalculates layout.
Follow me on LinkedIn:
without affecting layout.
Example:
div.style.width = "200px"; /* triggers reflow + repaint */
div.style.background = "red"; /* triggers repaint only */
Key Takeaway:
Minimize layout changes; batch DOM updates to improve performance.
JavaScript JavaScript Tutorial · JavaScript
height, margin, and padding.
Example:
.block {
display: block;
width: 100px;
.inline-block {
display: inline-block;
width: 100px;
Key Takeaway:
inline-block combines the flow of inline with the flexibility of block.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
CSS stands for Cascading Style Sheets.
It is used to style and layout HTML elements — controlling colors, fonts, spacing, and
responsiveness.
Key Takeaway:
CSS separates design from content, improving flexibility and maintainability.
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
HTML stands for HyperText Markup Language. It is the standard language used to create
and structure content on web pages.
Example:
A simple HTML document:
<!DOCTYPE html>
<html>
<head>
Follow me on LinkedIn:
<title>My First Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
Key Takeaway:
HTML defines the structure; CSS styles it; JavaScript makes it interactive.
JavaScript JavaScript Tutorial · JavaScript
The browser reads HTML line-by-line and builds a DOM (Document Object Model)
tree.
JavaScript JavaScript Tutorial · JavaScript
When a browser loads a webpage, it goes through these main steps:
JavaScript JavaScript Tutorial · JavaScript
JavaScript is a high-level, interpreted, dynamic programming language used to make
web pages interactive and dynamic. It runs in browsers and also on servers (using
Node.js).
JavaScript JavaScript Tutorial · JavaScript
Follow me on LinkedIn:
Bootstrap is a popular front-end framework for building responsive, mobile-first web pages
using HTML, CSS, and JavaScript components.
JavaScript JavaScript Tutorial · JavaScript
These are semantic elements that help structure a webpage meaningfully:
Follow me on LinkedIn:
Example:
<section>
<article>
<h2>HTML Interview Guide</h2>
<p>Learn important HTML concepts easily.</p>
</article>
<aside>
<p>Check out our CSS guide next!</p>
</aside>
</section>
Key Takeaway:
Use these for clear content hierarchy and SEO-friendly structure.
JavaScript JavaScript Tutorial · JavaScript
Flexbox (Flexible Box Layout) is a one-dimensional layout system for aligning items
horizontally or vertically.
Example:
.container {
display: flex;
justify-content: center;
align-items: center;
Why use it:
Key Takeaway:
Flexbox simplifies alignment and space distribution in one direction.
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
✅ Responsive design
✅ Pre-styled components
✅ Cross-browser compatibility
✅ Customizable via variables and themes
✅ Speeds up development
JavaScript JavaScript Tutorial · JavaScript
✅ Best Practices:
Key Takeaway:
Efficient CSS = fewer reflows, fewer repaints, and lightweight selectors.
JavaScript JavaScript Tutorial · JavaScript
There are three ways to include CSS:
Inline CSS:
<p style="color: blue;">Hello!</p>
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
ARIA (Accessible Rich Internet Applications) roles make web content more accessible
for users relying on assistive technologies (like screen readers).
Example:
<button role="switch" aria-checked="false">Dark Mode</button>
Follow me on LinkedIn:
Key Takeaway:
ARIA makes dynamic interfaces accessible by adding semantic meaning beyond native
HTML.
JavaScript JavaScript Tutorial · JavaScript
CSS is parsed into a CSSOM (CSS Object Model).
JavaScript may modify the DOM or halt parsing (especially with synchronous
scripts).
JavaScript JavaScript Tutorial · JavaScript
The event loop manages asynchronous operations in JavaScript.
It continuously checks the call stack and callback queue — executing queued tasks once
the stack is empty.
Example:
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
// Output: A, C, B
Even though setTimeout is 0ms, it runs after the main thread finishes due to the event
loop.
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
The <!DOCTYPE html> declaration tells the browser which version of HTML the page
uses.
In modern websites, it triggers HTML5 standards mode, ensuring consistent rendering
across browsers.
Example:
<!DOCTYPE html>
<html>
...
</html>
Key Takeaway:
Always include <!DOCTYPE html> at the top of every HTML file.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
V8 is Google’s open-source JavaScript engine used in Chrome and Node.js.
It:
JavaScript JavaScript Tutorial · JavaScript
Follow me on LinkedIn:
Example:
<img src="logo.png" alt="Company Logo">
Here, <img> is a tag, and src & alt are attributes.
Key Takeaway:
Tags = structure; Attributes = extra information.
JavaScript JavaScript Tutorial · JavaScript
A callback is a function passed as an argument to another function to be executed after
some operation completes.
Example:
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 1000);
Follow me on LinkedIn:
fetchData(console.log);
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
The <canvas> element is used to draw graphics, animations, charts, or games using
JavaScript.
Example:
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 180, 80);
</script>
Follow me on LinkedIn:
Key Takeaway:
<canvas> gives you a pixel-based drawing area inside HTML — perfect for dynamic
graphics.
JavaScript JavaScript Tutorial · JavaScript
Element selector: Targets HTML tags.
p { color: green; }
JavaScript JavaScript Tutorial · JavaScript
Use classes for reusable styles, IDs for unique elements.
JavaScript JavaScript Tutorial · JavaScript
Keyword Scope Re-declar
Re-assig
Hoisted?
var Functio
✅ Yes ✅ Yes ✅ Yes (undefined)
let Block ❌ No ✅ Yes 🚫 Temporarily dead
zone
const Block ❌ No ❌ No 🚫 Temporarily dead
zone
Example:
Follow me on LinkedIn:
let x = 10; const y = 20; var z = 30;
JavaScript JavaScript Tutorial · JavaScript
Example:
<user-card></user-card>
<template id="user-template">
<p>Hello, <span id="name"></span></p>
</template>
<script>
class UserCard extends HTMLElement {
connectedCallback() {
const tmpl = document.getElementById("user-template");
const content = tmpl.content.cloneNode(true);
content.querySelector("#name").textContent = "Sandeep";
this.appendChild(content);
customElements.define("user-card", UserCard);
</script>
Key Takeaway:
Web Components = reusable, encapsulated building blocks for modern web apps.
JavaScript JavaScript Tutorial · JavaScript
The Shadow DOM is a web component feature that encapsulates a section of the DOM —
meaning styles and markup inside it don’t leak out or get affected by the rest of the page.
Example:
<custom-card></custom-card>
<script>
class CustomCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `<style>p { color: blue; }</style><p>Hello
Shadow!</p>`;
customElements.define('custom-card', CustomCard);
</script>
Key Takeaway:
Shadow DOM = style and structure isolation for reusable, predictable components.
JavaScript JavaScript Tutorial · JavaScript
DOM + CSSOM = Render Tree (a visual structure of elements and styles).
JavaScript JavaScript Tutorial · JavaScript
Feature Flexbox Grid
Layout One-dimensional (row or column) Two-dimensional (rows and columns)
Use Case Aligning items in a line Building full-page layouts
Alignment Easier for single direction Easier for full layout structure
Example:
/* Flexbox */
display: flex;
/* Grid */
Follow me on LinkedIn:
display: grid;
grid-template-columns: repeat(3, 1fr);
Key Takeaway:
Use Flexbox for alignment; Grid for complete layouts.
JavaScript JavaScript Tutorial · JavaScript
Feature Bootstrap 4 Bootstrap 5
jQuery Required Removed
Grid 5 breakpoints 6 (added xxl)
Forms Legacy Redesigned
Icons None Separate Bootstrap Icons
Utility API Limited Expanded and
customizable
JavaScript JavaScript Tutorial · JavaScript
Garbage collection automatically frees memory that’s no longer referenced.
The V8 engine uses the mark-and-sweep algorithm:
Example:
let user = { name: "John" };
user = null; // eligible for garbage collection
JavaScript JavaScript Tutorial · JavaScript
Use the prefers-color-scheme media query or toggle themes via classes.
Example (automatic via system theme):
Follow me on LinkedIn:
@media (prefers-color-scheme: dark) {
body {
background: #121212;
color: #fff;
Example (manual toggle):
body.dark-mode {
background: #000;
color: white;
Key Takeaway:
Dark mode can adapt automatically or via user preference toggles.
JavaScript JavaScript Tutorial · JavaScript
Preprocessors extend CSS with variables, nesting, mixins, and functions, compiled into
plain CSS.
Example (SASS):
$main-color: #3498db;
.button {
background: $main-color;
&:hover { background: darken($main-color, 10%); }
Key Takeaway:
Preprocessors make CSS more modular, maintainable, and reusable.
JavaScript JavaScript Tutorial · JavaScript
The browser calculates positions (layout) and then paints pixels on the screen.
Key Takeaway:
The DOM is built first, then styles are applied, and finally pixels are rendered — optimizing
this pipeline improves page performance.
JavaScript JavaScript Tutorial · JavaScript
Metho
Purpose Arguments Invokes
Immediately?
call(
Call a function with a specific this Comma-separat
✅ Yes
apply
Same as call(), but takes array Array ✅ Yes
bind(
Returns a new function with fixed
this
Comma-separat
❌ No
Example:
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
const user = { name: "John" };
greet.call(user, "Hi");
greet.apply(user, ["Hello"]);
const bound = greet.bind(user, "Hey");
bound();
JavaScript JavaScript Tutorial · JavaScript
SEO optimization starts with clean, structured, and semantic HTML.
Best practices:
Follow me on LinkedIn:
(<h1> → <h6>).
Example:
<meta name="description" content="Learn web development step-by-step
with examples.">
<h1>HTML Interview Questions</h1>
Key Takeaway:
SEO-friendly HTML = clear structure + accurate metadata + accessible content.
JavaScript JavaScript Tutorial · JavaScript
Variables are containers to store data.
Example: let age = 25;
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
Example:
<div>Block Section</div>
<p>This is a <span style="color: red;">red word</span> in a
sentence.</p>
Key Takeaway:
Use <div> for layout; <span> for inline styling.
JavaScript JavaScript Tutorial · JavaScript
Hoisting is JavaScript’s behavior of moving variable and function declarations to the
top of their scope during compilation.
Example:
console.log(a); // undefined
var a = 5;
Here, var a is hoisted but not initialized.
JavaScript JavaScript Tutorial · JavaScript
A service worker is a background script that runs independently of the web page.
It enables offline caching, push notifications, and background sync.
Example:
navigator.serviceWorker.register('/sw.js');
✅ Used in Progressive Web Apps (PWAs).
JavaScript JavaScript Tutorial · JavaScript
Both store data in the browser, but they differ in duration and scope.
Feature localStorage sessionStorage
Lifetime Until manually cleared Until the tab is closed
Scope Shared across tabs Specific to one tab
Capacity ~5–10MB ~5MB
Example:
localStorage.setItem("username", "Sandeep");
sessionStorage.setItem("theme", "dark");
Key Takeaway:
Use localStorage for long-term data; sessionStorage for temporary, tab-specific data.
JavaScript JavaScript Tutorial · JavaScript
Type Scope Example Priority
Inline Single element style="color:re
d;"
Highest
Internal One page <style> inside
<head>
Medium
External Multiple pages Linked .css file Lowest
Key Takeaway:
Use external CSS for maintainable, large-scale projects.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Use fractional units (fr) and media queries.
Example:
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 10px;
Key Takeaway:
auto-fit and minmax() automatically adapt the grid to screen size.
JavaScript JavaScript Tutorial · JavaScript
Example:
div {
width: 100px;
padding: 10px;
border: 5px solid black;
margin: 20px;
Key Takeaway:
Total width = content + padding + border + margin.
JavaScript JavaScript Tutorial · JavaScript
A container wraps page content and provides horizontal padding.
<div class="container">Content</div>
<div class="container-fluid">Full width</div>
JavaScript JavaScript Tutorial · JavaScript
Lazy loading defers loading of non-critical images or iframes until they are visible in the
viewport — improving page speed.
Example:
<img src="photo.jpg" loading="lazy" alt="Nature view">
Key Takeaway:
loading="lazy" helps reduce initial load time and saves bandwidth.
JavaScript JavaScript Tutorial · JavaScript
Use the <a> tag with the href attribute.
Example:
<a href="
target="_blank">Visit Google</a>
Explanation:
Follow me on LinkedIn:
Key Takeaway:
Always add descriptive link text for accessibility.
JavaScript JavaScript Tutorial · JavaScript
They let you embed audio and video files directly in HTML without plugins like Flash.
Example:
<audio controls>
<source src="music.mp3" type="audio/mpeg">
</audio>
<video controls width="320">
<source src="movie.mp4" type="video/mp4">
</video>
Follow me on LinkedIn:
Key Takeaway:
HTML5 makes multimedia playback native, fast, and accessible.
JavaScript JavaScript Tutorial · JavaScript
In JavaScript, every object can inherit properties from another object called its prototype.
This enables object reusability.
Example:
const animal = { eats: true };
const dog = Object.create(animal);
Follow me on LinkedIn:
dog.barks = true;
console.log(dog.eats); // true (inherited)
JavaScript JavaScript Tutorial · JavaScript
A Promise represents a value that may be available now, later, or never.
It helps handle asynchronous operations in a cleaner way.
Follow me on LinkedIn:
Example:
fetch('/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
✅ async/await simplifies promise syntax.
JavaScript JavaScript Tutorial · JavaScript
Functions are blocks of reusable code that perform a specific task.
Example:
function greet(name) {
return `Hello, ${name}`;
JavaScript JavaScript Tutorial · JavaScript
Example:
p { color: black; } /* low */
#intro { color: blue; } /* higher */
<p id="intro" style="color:red;">text</p> <!-- highest -->
Key Takeaway:
Use balanced specificity; avoid overuse of !important.
JavaScript JavaScript Tutorial · JavaScript
Follow me on LinkedIn:
Aspect @import <link>
Loaded Inside CSS Inside HTML
<head>
Performance Slower (sequential) Faster (parallel)
Media Queries Can include Can include
Recommended
❌ Avoid ✅ Preferred
Key Takeaway:
Use <link> — it loads faster and supports preloading and caching better.
JavaScript JavaScript Tutorial · JavaScript
Makes an element toggle between relative and fixed based on scroll position.
Example:
header {
position: sticky;
top: 0;
background: white;
Follow me on LinkedIn:
Key Takeaway:
sticky elements stay visible within their parent container while scrolling.
JavaScript JavaScript Tutorial · JavaScript
Bootstrap uses a 12-column grid based on flexbox.
You divide your layout using .row and .col-* classes.
Follow me on LinkedIn:
<div class="row">
<div class="col-6">Half</div>
<div class="col-6">Half</div>
</div>
JavaScript JavaScript Tutorial · JavaScript
Operator Description Example
== Compares values after type
conversion
'5' == 5 →
true
=== Compares values and types '5' === 5 →
false
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Web Workers allow JavaScript to run code in background threads, keeping the UI
responsive.
Example:
// main.js
const worker = new Worker('worker.js');
worker.postMessage('Start');
// worker.js
onmessage = e => postMessage('Task done');
JavaScript JavaScript Tutorial · JavaScript
They help browsers pick the best image for the user’s device and screen size.
Follow me on LinkedIn:
Example:
<img
src="small.jpg"
srcset="medium.jpg 768w, large.jpg 1200w"
sizes="(max-width: 768px) 100vw, 50vw"
alt="Landscape">
Key Takeaway:
srcset + sizes = responsive images that load efficiently across devices.
JavaScript JavaScript Tutorial · JavaScript
✅ Common techniques:
Use feature queries:
@supports (display: grid) {
.container { display: grid; }
Provide fallbacks for older browsers:
background: #000;
background: linear-gradient(to right, #000, #333);
Key Takeaway:
Graceful degradation and progressive enhancement keep CSS cross-browser safe.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
ES6 introduced modules for code reusability and organization.
They use export and import keywords.
Example:
// math.js
export function add(a, b) { return a + b; }
// main.js
import { add } from './math.js';
JavaScript JavaScript Tutorial · JavaScript
Property Description
min-wid
Element won’t shrink below this width
max-wid
Element won’t grow beyond this width
Example:
div {
min-width: 200px;
max-width: 600px;
Key Takeaway:
Use both for responsive, constrained resizing.
JavaScript JavaScript Tutorial · JavaScript
Add the draggable="true" attribute and use drag events in JavaScript.
Example:
<p id="drag1" draggable="true" ondragstart="drag(event)">Drag
me!</p>
<script>
function drag(e) {
e.dataTransfer.setData("text", e.target.id);
</script>
Key Takeaway:
Use draggable="true" plus ondragstart and ondrop to enable drag-and-drop
functionality.
JavaScript JavaScript Tutorial · JavaScript
Breakpoints define responsive screen widths:
Breakpoint Prefix Size
Extra small none <576px
Small sm ≥576px
Medium md ≥768px
Large lg ≥992px
Extra large xl ≥1200px
XXL xxl ≥1400px
JavaScript JavaScript Tutorial · JavaScript
Pseudo-class: targets an element’s state.
a:hover { color: red; }
Pseudo-element: targets part of an element.
p::first-line { font-weight: bold; }
Follow me on LinkedIn:
Key Takeaway:
:hover changes behavior; ::before and ::after insert content.
JavaScript JavaScript Tutorial · JavaScript
Semantic elements clearly describe their purpose in the document structure.
Examples include: <header>, <footer>, <article>, <nav>, <section>.
Example:
<article>
<h2>Breaking News</h2>
<p>New tech trends are emerging every day.</p>
</article>
Key Takeaway:
Semantic tags improve SEO and accessibility.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Use @keyframes and the animation property.
Example:
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
.box {
animation: fadeIn 2s ease-in-out;
Follow me on LinkedIn:
Key Takeaway:
@keyframes define the animation steps; animation applies them.
JavaScript JavaScript Tutorial · JavaScript
The <head> tag contains metadata — information about the document that isn’t displayed
on the page (like title, styles, or scripts).
Example:
<head>
<title>Portfolio</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
Follow me on LinkedIn:
Key Takeaway:
Think of <head> as your page’s control room.
JavaScript JavaScript Tutorial · JavaScript
Example:
<script>
document.write("JavaScript is enabled!");
Follow me on LinkedIn:
</script>
<noscript>
<p>Please enable JavaScript to view this content.</p>
</noscript>
Key Takeaway:
<noscript> provides graceful fallback content.
JavaScript JavaScript Tutorial · JavaScript
Semantic HTML elements (like <nav>, <main>, <form>, <button>) provide meaning to
content — making it easier for assistive technologies to navigate.
Example:
<nav aria-label="Main navigation">
<a href="#home">Home</a>
<a href="#about">About</a>
</nav>
Advantages:
Key Takeaway:
Semantics = communication between developers, browsers, and accessibility tools.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
BEM is a naming convention for writing scalable and reusable CSS.
Structure:
.block__element--modifier
Example:
<div class="card card--featured">
<h2 class="card__title">Profile</h2>
</div>
Key Takeaway:
BEM enforces clarity:
JavaScript JavaScript Tutorial · JavaScript
Use the grid system and responsive classes:
<div class="col-12 col-md-6 col-lg-4">Responsive column</div>
JavaScript JavaScript Tutorial · JavaScript
Template literals allow embedded expressions and multi-line strings using backticks
(`).
Example:
let name = "John";
console.log(`Hello, ${name}!`);
JavaScript JavaScript Tutorial · JavaScript
Used to expand arrays or objects into individual elements.
Example:
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5]
JavaScript JavaScript Tutorial · JavaScript
Example:
{a:1} === {a:1} // false (different refs)
Use libraries like Lodash’s _.isEqual() for deep comparison.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Using Flexbox:
.parent {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 100vh;
Key Takeaway:
flexbox is the easiest and modern way to center elements.
JavaScript JavaScript Tutorial · JavaScript
Position Based On Moves with Page
Scroll?
Relative Its normal position ✅ Yes
Absolut
Nearest positioned
ancestor
✅ Yes
Fixed Viewport ❌ No
Example:
div { position: absolute; top: 10px; left: 20px; }
Key Takeaway:
Absolute is relative to parent; fixed stays on screen.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Values that evaluate to false in Boolean context:
false, 0, "", null, undefined, NaN
Example:
if (!0) console.log("Falsy"); // prints "Falsy"
JavaScript JavaScript Tutorial · JavaScript
Web Components are reusable custom elements built with:
JavaScript JavaScript Tutorial · JavaScript
Transitions animate property changes smoothly.
Example:
button {
background: blue;
transition: background 0.3s ease;
button:hover {
background: red;
Key Takeaway:
Transitions are great for hover effects and simple UI feedback.
JavaScript JavaScript Tutorial · JavaScript
Predefined classes that handle spacing, display, text, alignment, etc.
Example:
<p class="text-center m-3 p-2">Centered text</p>
JavaScript JavaScript Tutorial · JavaScript
The rest operator ... collects multiple arguments into an array.
Example:
function sum(...nums) {
return nums.reduce((a, b) => a + b);
Follow me on LinkedIn:
console.log(sum(1, 2, 3)); // 6
JavaScript JavaScript Tutorial · JavaScript
Use CSS or the HTML5 srcset and sizes attributes.
HTML Example:
<img
src="small.jpg"
srcset="medium.jpg 768w, large.jpg 1200w"
sizes="(max-width: 768px) 100vw, 50vw"
alt="Mountain view">
CSS Example:
img {
max-width: 100%;
height: auto;
Key Takeaway:
Responsive images adjust to different screen sizes for faster load and better UX.
JavaScript JavaScript Tutorial · JavaScript
Use the <img> tag with the src and alt attributes.
Example:
<img src="images/photo.jpg" alt="A sunset at the beach">
Key Takeaway:
The alt attribute improves accessibility and helps SEO.
JavaScript JavaScript Tutorial · JavaScript
A closure is when a function remembers variables from its outer scope even after the
outer function has finished executing.
Example:
function counter() {
let count = 0;
return function() {
count++;
return count;
const add = counter();
console.log(add()); // 1
JavaScript JavaScript Tutorial · JavaScript
JS manages memory via automatic garbage collection.
Memory allocation happens when objects are created, and deallocation occurs when they’re
no longer reachable.
Example:
Creating large arrays without clearing references may cause memory leaks.
JavaScript JavaScript Tutorial · JavaScript
Specificity determines which rule wins when multiple styles target the same element.
Priority order (lowest → highest):
JavaScript JavaScript Tutorial · JavaScript
calc() performs dynamic calculations for CSS values.
Example:
div {
width: calc(100% - 50px);
padding: calc(1em + 5px);
Follow me on LinkedIn:
Key Takeaway:
calc() mixes units and adjusts layouts dynamically.
JavaScript JavaScript Tutorial · JavaScript
Returns the type of a variable.
Example:
typeof "hello"; // "string"
typeof 42; // "number"
JavaScript JavaScript Tutorial · JavaScript
Method Returns Chainable Use Case
forEach
undefin
❌ No Iteration
map() New array ✅ Yes Transformation
Example:
[1,2,3].map(x => x*2); // [2,4,6]
JavaScript JavaScript Tutorial · JavaScript
Proxy allows you to intercept and redefine fundamental operations on objects.
Example:
const user = { name: "Alice" };
const proxy = new Proxy(user, {
get: (target, prop) => `${prop} -> ${target[prop]}`
});
console.log(proxy.name); // name -> Alice
✅ Used in data validation, reactive frameworks (like Vue.js).
JavaScript JavaScript Tutorial · JavaScript
z-index controls stacking order of overlapping elements.
Example:
.box1 { z-index: 1; }
.box2 { z-index: 10; }
Higher values appear on top.
Key Takeaway:
Only works on positioned elements (position ≠ static).
JavaScript JavaScript Tutorial · JavaScript
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
It hints the browser that an element will soon change, so the browser can optimize
rendering ahead of time.
Example:
.box {
will-change: transform, opacity;
Key Takeaway:
Improves animation performance but use carefully — too many can waste memory.
JavaScript JavaScript Tutorial · JavaScript
Example:
<ol>
<li>HTML</li>
<li>CSS</li>
</ol>
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
Follow me on LinkedIn:
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language</dd>
</dl>
Key Takeaway:
Choose list type based on how you want to present data.
JavaScript JavaScript Tutorial · JavaScript
It links human-readable text with a machine-readable value — useful for analytics or scripts.
Follow me on LinkedIn:
Example:
<p>Price: <data value="499">₹499</data></p>
Key Takeaway:
<data> helps embed structured data inside readable content.
JavaScript JavaScript Tutorial · JavaScript
Arrow functions are a shorter syntax for writing functions. They don’t have their own
this.
Example:
const sum = (a, b) => a + b;
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Via CDN:
<link
href="
p.min.css" rel="stylesheet">
Or via NPM:
npm install bootstrap
Intermediate
JavaScript JavaScript Tutorial · JavaScript
contain tells the browser which aspects of an element’s rendering are independent
from the rest of the document — reducing reflows and repaints.
Example:
.card {
Follow me on LinkedIn:
contain: layout paint;
Key Takeaway:
Containment isolates elements for performance optimization.
JavaScript JavaScript Tutorial · JavaScript
It completely hides the element — it’s not visible and doesn’t take up space in the layout.
Example:
.hidden { display: none; }
Key Takeaway:
display: none removes the element from the document flow.
JavaScript JavaScript Tutorial · JavaScript
The <meta> tag provides metadata — like page description, author, and viewport settings.
Example:
<meta name="description" content="Learn web development with real
examples.">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
Key Takeaway:
Meta tags are essential for SEO and responsive design.
JavaScript JavaScript Tutorial · JavaScript
Instead of attaching listeners to every element, attach one listener to a parent — it
captures events from its children using bubbling.
Example:
document.querySelector('#list').addEventListener('click', e => {
if (e.target.tagName === 'LI') console.log(e.target.textContent);
});
Follow me on LinkedIn:
✅ Improves performance and memory usage.
JavaScript JavaScript Tutorial · JavaScript
Generators are special functions that can pause and resume execution using the
function* syntax and yield.
Example:
function* counter() {
yield 1;
yield 2;
const gen = counter();
console.log(gen.next().value); // 1
JavaScript JavaScript Tutorial · JavaScript
Example:
<div id="main-header"></div>
<div class="card"></div>
<div class="card"></div>
Key Takeaway:
Use id for specific targeting; class for grouping and styling.
JavaScript JavaScript Tutorial · JavaScript
Set equal height and width and use border-radius: 50%.
Example:
.circle {
width: 100px;
height: 100px;
background: teal;
border-radius: 50%;
Key Takeaway:
Equal dimensions + border-radius: 50% = perfect circle.
JavaScript JavaScript Tutorial · JavaScript
Example:
5 == '5'; // true
5 === '5'; // false
🔹 2. Functions and Scope – Q&A
JavaScript JavaScript Tutorial · JavaScript
Use the W3C HTML Validator to check your markup.
To fix errors:
Example:
✅ Correct:
<img src="logo.png" alt="Company Logo">
❌ Incorrect:
<img src="logo.png" alt=Company Logo>
Follow me on LinkedIn:
Key Takeaway:
Clean, valid HTML ensures better rendering, SEO, and accessibility.
JavaScript JavaScript Tutorial · JavaScript
Objects store data in key-value pairs.
Example:
const user = { name: "Alice", age: 25 };
console.log(user.name); // Alice
JavaScript JavaScript Tutorial · JavaScript
The <template> tag defines reusable HTML that isn’t rendered until you activate it via
JavaScript.
Example:
<template id="card-template">
<div class="card">
<h3></h3>
<p></p>
</div>
</template>
<script>
const tmpl = document.getElementById("card-template");
const clone = tmpl.content.cloneNode(true);
clone.querySelector("h3").textContent = "HTML Tips";
clone.querySelector("p").textContent = "Use semantic tags for SEO.";
document.body.appendChild(clone);
</script>
Key Takeaway:
<template> = invisible HTML blueprint ready to be cloned dynamically.
JavaScript JavaScript Tutorial · JavaScript
Logical properties adapt layouts for different writing directions (LTR, RTL, vertical text).
Physical Logical
margin-le
margin-inline-s
tart
padding-t
padding-block-s
tart
Example:
p {
padding-inline-start: 10px; /* Works for both LTR and RTL */
Key Takeaway:
Logical properties make designs multilingual and direction-aware.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Use visibility: hidden;
Example:
.invisible { visibility: hidden; }
Follow me on LinkedIn:
Key Takeaway:
Hidden = invisible but occupies space.
display: none = gone completely.
JavaScript JavaScript Tutorial · JavaScript
Use <table>, <tr> (row), <th> (header cell), and <td> (data cell).
Example:
<table border="1">
<tr>
<th>Name</th>
<th>Role</th>
</tr>
<tr>
<td>Sandeep</td>
Follow me on LinkedIn:
<td>Developer</td>
</tr>
</table>
Key Takeaway:
Tables are for data — not for layout.
JavaScript JavaScript Tutorial · JavaScript
const arr1 = [1, 2, 3];
const arr2 = new Array(1, 2, 3);
JavaScript JavaScript Tutorial · JavaScript
Currying transforms a function that takes multiple arguments into a sequence of functions
that take one argument each.
Example:
function add(a) {
return b => a + b;
console.log(add(5)(3)); // 8
✅ Useful for function reusability and functional composition.
JavaScript JavaScript Tutorial · JavaScript
A function is a block of reusable code that performs a task or returns a value.
Example:
function greet(name) {
return `Hello, ${name}!`;
console.log(greet("Sandeep"));
JavaScript JavaScript Tutorial · JavaScript
async/await makes asynchronous code look synchronous.
It works with Promises.
Follow me on LinkedIn:
Example:
async function fetchData() {
const data = await fetch("/api");
return data.json();
JavaScript JavaScript Tutorial · JavaScript
<iframe> embeds another HTML page inside the current page.
Example:
<iframe src="
width="500" height="300"></iframe>
Key Takeaway:
Use iframes to display external content, but avoid excessive use for performance and SEO
reasons.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
@keyframes define the steps of an animation over time.
Example:
@keyframes moveBox {
0% { left: 0; }
100% { left: 200px; }
.box {
position: relative;
animation: moveBox 2s linear infinite;
Follow me on LinkedIn:
Key Takeaway:
Keyframes control how elements move, rotate, or fade during animation.
JavaScript JavaScript Tutorial · JavaScript
Functions that execute immediately after being defined.
Example:
(function() {
console.log("Runs instantly!");
})();
Used to create private scopes before let and const.
JavaScript JavaScript Tutorial · JavaScript
An event listener waits for user actions (like clicks or keypresses) and runs a
function when the event occurs.
Example:
button.addEventListener("click", () => alert("Clicked!"));
JavaScript JavaScript Tutorial · JavaScript
Controls what happens when content exceeds the container’s size.
Values:
Example:
div { overflow: auto; }
Key Takeaway:
overflow: auto adds scrollbars only when needed.
JavaScript JavaScript Tutorial · JavaScript
It defines a shape that clips (hides) parts of an element.
Example:
.image {
clip-path: circle(50% at 50% 50%);
Key Takeaway:
clip-path creates creative shapes like circles, polygons, or custom SVG paths.
JavaScript JavaScript Tutorial · JavaScript
GPU acceleration is triggered when you use transform, opacity, or will-change.
It moves rendering to the GPU, making animations smoother.
Example:
.box {
transform: translateZ(0);
Follow me on LinkedIn:
Key Takeaway:
Use GPU-friendly properties for smoother transitions; avoid triggering layout changes.
JavaScript JavaScript Tutorial · JavaScript
It collects user input and sends it to a server or script for processing.
Example:
<form action="/submit" method="POST">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
Key Takeaway:
Forms are the foundation of user interaction on the web.
JavaScript JavaScript Tutorial · JavaScript
Cards are flexible content containers for images, text, and links.
<div class="card" style="width:18rem;">
<img src="..." class="card-img-top">
<div class="card-body">...</div>
</div>
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Browsers are forgiving — they use an HTML parser that tries to fix mistakes automatically.
For example, missing closing tags are inferred.
Example:
<p>This is valid
Follow me on LinkedIn:
<p>This is auto-closed by browser</p>
Key Takeaway:
Browsers recover from errors, but writing valid HTML ensures consistent rendering.
JavaScript JavaScript Tutorial · JavaScript
Variables declared inside a function are accessible only within that function.
Example:
function demo() {
let x = 10;
console.log(x); // 10
console.log(x); // ReferenceError
JavaScript JavaScript Tutorial · JavaScript
YouTube provides an embed link using <iframe>.
Example:
<iframe
width="560"
height="315"
src="
allowfullscreen>
</iframe>
Key Takeaway:
Always use the /embed/ URL format for proper YouTube embedding.
JavaScript JavaScript Tutorial · JavaScript
Both create objects, but:
Example:
const a = {}; // Preferred
const b = new Object(); // Not preferred
JavaScript JavaScript Tutorial · JavaScript
CSS Houdini is a set of APIs that let developers extend CSS by writing code that hooks
directly into the CSS engine.
Examples:
Example (Paint API):
registerPaint('dots', class {
paint(ctx, size) {
ctx.fillStyle = 'red';
ctx.arc(50, 50, 10, 0, 2 * Math.PI);
ctx.fill();
});
Key Takeaway:
Houdini gives developers low-level control over how CSS works under the hood.
JavaScript JavaScript Tutorial · JavaScript
Entities display reserved characters (like <, >, &) or symbols not on the keyboard.
Example:
<p>Use <div> for containers and & for ampersands.</p>
Key Takeaway:
Entities prevent HTML from confusing symbols with code.
JavaScript JavaScript Tutorial · JavaScript
Functions that:
Example:
function add(a, b) {
return a + b; // pure
JavaScript JavaScript Tutorial · JavaScript
A polyfill is a piece of code that adds a feature missing in older browsers.
Follow me on LinkedIn:
Example:
if (!Array.prototype.includes) {
Array.prototype.includes = function(item) {
return this.indexOf(item) !== -1;
JavaScript JavaScript Tutorial · JavaScript
Variables declared with let or const inside curly braces {} are accessible only within
that block.
Example:
if (true) {
let y = 20;
const z = 30;
// console.log(y, z); // ReferenceError
JavaScript JavaScript Tutorial · JavaScript
<picture> allows serving different image versions depending on device, screen size, or
media type.
Example:
<picture>
<source srcset="photo-large.jpg" media="(min-width: 800px)">
<source srcset="photo-small.jpg" media="(max-width: 799px)">
<img src="photo-default.jpg" alt="Beautiful landscape">
</picture>
Key Takeaway:
Use <picture> for art direction — showing different images per device or context.
JavaScript JavaScript Tutorial · JavaScript
Example:
<head>
<title>My Portfolio</title>
</head>
<header>
<h1>Welcome to My Portfolio</h1>
</header>
Follow me on LinkedIn:
Key Takeaway:
<head> = document info; <header> = visible header area.
JavaScript JavaScript Tutorial · JavaScript
Modals are created using the .modal class and toggled with JS or data attributes.
<button data-bs-toggle="modal"
data-bs-target="#myModal">Open</button>
<div class="modal fade" id="myModal">
<div class="modal-dialog"><div
class="modal-content">...</div></div>
</div>
JavaScript JavaScript Tutorial · JavaScript
Type Meaning
null Intentional absence of value
undefin
Variable declared but not
assigned
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Use the following combination:
p {
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
Key Takeaway:
Truncates long text with “…” when it exceeds container width.
JavaScript JavaScript Tutorial · JavaScript
Property Location Affects
Background?
Padding Inside border ✅ Yes
Margin Outside border ❌ No
Example:
div {
Follow me on LinkedIn:
margin: 10px;
padding: 20px;
Key Takeaway:
Padding = inner spacing, Margin = outer spacing.
JavaScript JavaScript Tutorial · JavaScript
Add the lang attribute in the <html> tag.
Example:
<html lang="en">
Key Takeaway:
Helps screen readers and search engines understand the page’s language.
JavaScript JavaScript Tutorial · JavaScript
Defines how images or videos resize within their container.
Follow me on LinkedIn:
Example:
img {
width: 100%;
height: 300px;
object-fit: cover;
Key Takeaway:
cover fills the box; contain fits the whole image inside.
JavaScript JavaScript Tutorial · JavaScript
NaN stands for “Not-a-Number”, representing an invalid numeric operation.
Example:
console.log("hello" / 2); // NaN
JavaScript JavaScript Tutorial · JavaScript
✅ Use CSS to improve readability and focus visibility:
Follow me on LinkedIn:
Maintain sufficient color contrast:
body { color: #111; background: #fff; }
Use :focus styles for keyboard users:
button:focus { outline: 2px solid #005fcc; }
Respect user preferences:
@media (prefers-reduced-motion: reduce) {
* { animation: none; }
Key Takeaway:
Accessible CSS ensures inclusivity for all users — especially keyboard and screen-reader
users.
JavaScript JavaScript Tutorial · JavaScript
Arrow functions are a shorter syntax for writing functions and do not have their own
this.
Example:
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
JavaScript JavaScript Tutorial · JavaScript
Reusable UI blocks like buttons, modals, navbars, forms, alerts, etc., that follow
Bootstrap’s design standards.
JavaScript JavaScript Tutorial · JavaScript
Example:
Follow me on LinkedIn:
<script src="main.js" defer></script>
<img src="hero.jpg" loading="lazy" alt="Hero image">
Key Takeaway:
Speed = smaller files, fewer requests, smarter loading.
JavaScript JavaScript Tutorial · JavaScript
Example:
let x = 10; // number
x = "text"; // allowed
JavaScript JavaScript Tutorial · JavaScript
Combinators define relationships between selectors.
Combinator Description Example
Descendant ( ) Any nested element div p
Child (>) Direct child only div >
Adjacent sibling (+) Immediately next element h1 + p
General sibling (~) All next siblings h1 ~ p
Key Takeaway:
Combinators refine selector targeting.
JavaScript JavaScript Tutorial · JavaScript
Performance:
increasing page load time.
SEO:
Best Practice:
Example:
<iframe src="
title="Location
Map"></iframe>
Key Takeaway:
Iframes isolate content — great for embedding, but can slow pages and weaken SEO.
Follow me on LinkedIn:
CSS Interview Questions
JavaScript JavaScript Tutorial · JavaScript
Selects elements based on their order within a parent.
Examples:
li:nth-child(2) { color: red; } /* 2nd item */
li:nth-child(odd) { background: #eee; } /* odd items */
li:nth-child(3n) { font-weight: bold; } /* every 3rd item */
Key Takeaway:
nth-child() gives you precise control over repeating patterns in lists or grids.
Advanced
JavaScript JavaScript Tutorial · JavaScript
Used to find the type of a variable.
typeof "Hello"; // "string"
typeof 10; // "number"
typeof null; // "object" (bug)
JavaScript JavaScript Tutorial · JavaScript
They allow you to store extra data on HTML elements — useful for scripts or dynamic
behavior.
Example:
<button data-user-id="101" data-role="admin">View Profile</button>
<script>
const btn = document.querySelector("button");
console.log(btn.dataset.userId); // 101
console.log(btn.dataset.role); // admin
</script>
Key Takeaway:
data-* attributes are perfect for embedding small pieces of custom data without affecting
layout.
Follow me on LinkedIn:
Advanced
JavaScript JavaScript Tutorial · JavaScript
<section>).
Example:
<div>Block</div>
<span>Inline</span>
Key Takeaway:
Block = structure; Inline = styling or small content.
JavaScript JavaScript Tutorial · JavaScript
Example:
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
// Output: 1, 3, 2
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
When an event occurs in a nested element:
Example:
element.addEventListener('click', handler, true); // capturing
element.addEventListener('click', handler, false); // bubbling
JavaScript JavaScript Tutorial · JavaScript
Images that automatically scale with the parent container using .img-fluid:
<img src="..." class="img-fluid" alt="Responsive image">
JavaScript JavaScript Tutorial · JavaScript
Targets elements with a specific class attribute.
Example:
.card { background-color: lightgray; }
<div class="card">Profile</div>
Follow me on LinkedIn:
Key Takeaway:
Classes are reusable; use them for consistent styling across elements.
JavaScript JavaScript Tutorial · JavaScript
It applies visual effects (like blur, brightness, or contrast) to the area behind an element.
Example:
.blur-bg {
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.3);
Key Takeaway:
Used for modern UI effects (like frosted glass) — supported in modern browsers only.
Follow me on LinkedIn:
JavaScript Interview Questions
JavaScript JavaScript Tutorial · JavaScript
Feature Regular Function Arrow Function
this Dynamic Lexical (inherits from parent)
Syntax function
f(){}
(a,b)=>a+b
Can be used as
constructor
✅ ❌
JavaScript JavaScript Tutorial · JavaScript
The alt attribute provides alternative text when an image fails to load and is read by
screen readers.
Example:
Follow me on LinkedIn:
<img src="team.jpg" alt="Our development team">
Key Takeaway:
Always include meaningful alt text — it’s good for accessibility and SEO.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
A function that accepts another function as a parameter or returns a function.
Example:
function multiplyBy(factor) {
return x => x * factor;
const double = multiplyBy(2);
console.log(double(5)); // 10
JavaScript JavaScript Tutorial · JavaScript
Type Description
Shallow
Copy
Copies top-level properties only
Deep Copy Copies all nested objects too
Follow me on LinkedIn:
Example:
const obj = { a: { b: 1 } };
const shallow = { ...obj }; // same reference
const deep = JSON.parse(JSON.stringify(obj)); // new copy
JavaScript JavaScript Tutorial · JavaScript
A style where functions are pure, stateless, and composable.
Example:
const double = x => x * 2;
const square = x => x * x;
const result = square(double(3)); // 36
JavaScript JavaScript Tutorial · JavaScript
Promises handle asynchronous operations. They represent a value that may be
available now, later, or never.
Example:
let promise = new Promise((resolve, reject) => {
resolve("Success!");
});
promise.then(res => console.log(res));
JavaScript JavaScript Tutorial · JavaScript
Unit Relative To Example
em Parent’s font size 2em = 2 × parent
font-size
rem Root (<html>) font
size
2rem = 2 × root font-size
Example:
html { font-size: 16px; }
p { font-size: 2rem; } /* = 32px */
Key Takeaway:
Use rem for consistent sizing across the document.
JavaScript JavaScript Tutorial · JavaScript
Decorators modify classes or methods at runtime.
Common in TypeScript and frameworks like Angular.
Example (TypeScript):
function log(target, key) {
console.log(`${key} was called`);
class Example {
@log
test() {}
JavaScript JavaScript Tutorial · JavaScript
A function passed as an argument to another function to be executed later.
Example:
function greet(name, callback) {
console.log(`Hello, ${name}`);
callback();
greet("Sandeep", () => console.log("Callback executed"));
JavaScript JavaScript Tutorial · JavaScript
Define a variable with --name and access it with var().
Example:
:root {
button {
background: var(--main-color);
padding: var(--padding);
Follow me on LinkedIn:
Key Takeaway:
CSS variables make styles dynamic and reusable.
JavaScript JavaScript Tutorial · JavaScript
Promise chaining allows multiple async tasks to run sequentially.
Example:
fetch('/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
JavaScript JavaScript Tutorial · JavaScript
DOM (Document Object Model) represents the structure of an HTML document as a
tree of objects, allowing JavaScript to access and manipulate elements dynamically.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Example:
<b>Warning:</b> Incorrect password.<br>
<strong>Warning:</strong> Incorrect password.
Key Takeaway:
Use <strong> for emphasis that affects meaning.
JavaScript JavaScript Tutorial · JavaScript
Use .navbar and .navbar-expand-* classes:
Follow me on LinkedIn:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Brand</a>
</nav>
JavaScript JavaScript Tutorial · JavaScript
Example:
<i>Book titles</i> are italicized.
Please <em>do not</em> touch that.
Follow me on LinkedIn:
Key Takeaway:
<em> adds importance — <i> adds style.
JavaScript JavaScript Tutorial · JavaScript
Using prototypes or classes.
Example (ES6):
class Animal {
eat() { console.log("Eating"); }
class Dog extends Animal {
bark() { console.log("Bark!"); }
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
A function that:
Example:
function sum(a, b) {
return a + b;
JavaScript JavaScript Tutorial · JavaScript
They are collections that hold weak references to objects — allowing garbage collection if
no other reference exists.
Example:
let obj = {};
let wm = new WeakMap();
wm.set(obj, "value");
obj = null; // entry removed automatically
JavaScript JavaScript Tutorial · JavaScript
Media queries apply styles based on device conditions (width, orientation, etc.).
Example:
@media (max-width: 768px) {
body { background-color: lightgray; }
Key Takeaway:
Media queries enable responsive design across devices.
JavaScript JavaScript Tutorial · JavaScript
JSON (JavaScript Object Notation) is a lightweight format for storing and transferring
data.
Example:
let obj = { name: "Bob" };
let json = JSON.stringify(obj); // Convert to JSON string
JavaScript JavaScript Tutorial · JavaScript
Provides consistent button styling:
<button class="btn btn-primary">Click</button>
JavaScript JavaScript Tutorial · JavaScript
Styled inputs, selects, and textareas:
<input type="text" class="form-control" placeholder="Enter name">
JavaScript JavaScript Tutorial · JavaScript
float moves elements to the left or right — allowing text and inline elements to wrap
around.
Example:
img { float: right; margin: 10px; }
Key Takeaway:
Used for text wrapping, but Flexbox/Grid is better for layout today.
JavaScript JavaScript Tutorial · JavaScript
A favicon is the small icon shown in the browser tab.
Example:
<link rel="icon" type="image/png" href="favicon.png">
Key Takeaway:
Favicons help brand your site in the browser.
JavaScript JavaScript Tutorial · JavaScript
Method Mutates Original? Purpose
slice(start, end) ❌ No Extracts portion
Follow me on LinkedIn:
splice(start, count,
...items)
✅ Yes Adds/removes
items
JavaScript JavaScript Tutorial · JavaScript
A function that calls itself until a base condition is met.
Example:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
console.log(factorial(5)); // 120
JavaScript JavaScript Tutorial · JavaScript
Async iterators allow looping over asynchronous data sources.
Example:
async function* fetchItems() {
yield await fetch('/item1');
yield await fetch('/item2');
for await (let item of fetchItems()) {
console.log(item);
JavaScript JavaScript Tutorial · JavaScript
localStorage stores key-value pairs in the browser permanently (until cleared).
Example:
localStorage.setItem("user", "Alice");
console.log(localStorage.getItem("user")); // Alice
JavaScript JavaScript Tutorial · JavaScript
Type Example Priority
Microtask Promise.then,
MutationObserver
Higher
Macrotask setTimeout, setInterval Lower
Example:
setTimeout(() => console.log("Macro"), 0);
Promise.resolve().then(() => console.log("Micro"));
// Output: Micro → Macro
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
It allows unpacking values from arrays or objects.
Example:
const [a, b] = [1, 2];
const { name, age } = { name: "John", age: 30 };
JavaScript JavaScript Tutorial · JavaScript
Example:
function greet(name) { // name = parameter
console.log(`Hello ${name}`);
greet("Sandeep"); // "Sandeep" = argument
🔹 3. Closures and Lexical Scope – Q&A
JavaScript JavaScript Tutorial · JavaScript
It defines the page title shown in the browser tab and search results.
Example:
<title>My Portfolio | </title>
Key Takeaway:
Make your titles descriptive for better SEO and UX.
Intermediate
JavaScript JavaScript Tutorial · JavaScript
Prefixes ensure CSS works across browsers before full support.
Example:
Follow me on LinkedIn:
.box {
border-radius: 10px; /* Standard */
Key Takeaway:
Vendor prefixes provide cross-browser compatibility for experimental features.
Intermediate
JavaScript JavaScript Tutorial · JavaScript
Use Flexbox utilities:
<div class="d-flex align-items-center" style="height:200px;">
<p>Vertically centered</p>
</div>
Advanced
What is the difference between order and offset classes?
<div class="col-md-4 order-2 offset-md-1"></div>
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Type Description Example
Synchronous Executes line by line for loop
Follow me on LinkedIn:
Asynchronou
Doesn’t block — runs later via callbacks,
promises
setTimeout,
fetch()
JavaScript JavaScript Tutorial · JavaScript
An optimization technique to cache function results for repeated inputs.
Example:
function memoize(fn) {
const cache = {};
return x => cache[x] || (cache[x] = fn(x));
JavaScript JavaScript Tutorial · JavaScript
They provide default values when no argument is passed.
Example:
function greet(name = "Guest") {
return `Hello, ${name}`;
JavaScript JavaScript Tutorial · JavaScript
Modules are separate files that export code and import it elsewhere, ensuring
encapsulation and reusability.
Example:
// export.js
export const PI = 3.14;
// import.js
import { PI } from './export.js';
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
The period between variable declaration and initialization where it cannot be accessed.
Example:
console.log(x); // ReferenceError
let x = 10;
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Closures work because functions remember the scope in which they were created,
allowing access to outer function variables even after the outer function finishes.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Bootstrap 5 uses Flexbox by default for its grid system and utilities (.d-flex,
.justify-content-*, .align-items-*).
JavaScript JavaScript Tutorial · JavaScript
Example – private counter:
function createCounter() {
let count = 0; // private variable
return {
increment: () => ++count,
decrement: () => --count
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.decrement()); // 0
JavaScript JavaScript Tutorial · JavaScript
Method Add
Props
Modify Delete
preventExtensio
ns()
❌ No ✅ Yes ✅ Yes
seal() ❌ No ✅ Yes ❌ No
freeze() ❌ No ❌ No ❌ No
JavaScript JavaScript Tutorial · JavaScript
Loop Used For Iterates Over
for Traditional
loop
Index/count
for...
Arrays/iterable
Values
for...
Objects Keys
Example:
for (let i in obj) console.log(i); // keys
for (let v of arr) console.log(v); // values
JavaScript JavaScript Tutorial · JavaScript
A safe way to access nested properties without throwing an error if something is
undefined or null.
Example:
console.log(user?.address?.city);
JavaScript JavaScript Tutorial · JavaScript
Context this Refers To
Follow me on LinkedIn:
Global window or global
Method The object owning the method
Constructor The new instance
Arrow function Lexical (surrounding) scope
Example:
const obj = {
value: 10,
show: function() { console.log(this.value); }
obj.show(); // 10
JavaScript JavaScript Tutorial · JavaScript
Use margin (m-*) and padding (p-*) utilities:
<div class="p-3 m-2 text-center"></div>
JavaScript JavaScript Tutorial · JavaScript
Yes. Variables inside the outer function cannot be accessed directly, only via inner
functions.
Example: See createCounter() above.
JavaScript JavaScript Tutorial · JavaScript
Arrow functions are shorter, and they don’t have their own this, arguments, or
prototype.
Follow me on LinkedIn:
Example:
const obj = {
val: 10,
normal() { console.log(this.val); }, // Works
arrow: () => console.log(this.val), // Undefined (no own this)
JavaScript JavaScript Tutorial · JavaScript
import { Button } from 'react-bootstrap';
<Button variant="primary">Click</Button>
JavaScript JavaScript Tutorial · JavaScript
Use try...catch inside async functions or .catch() for Promises.
Example:
async function loadData() {
try {
const res = await fetch('/data');
return await res.json();
} catch (err) {
console.error("Error:", err);
Follow me on LinkedIn:
Advanced
JavaScript JavaScript Tutorial · JavaScript
Both execute dynamic code, but:
Example:
eval("var a = 5");
const b = new Function("return 5;");
⚠ Both are discouraged due to security and performance issues.
Bootstrap Interview Questions
JavaScript JavaScript Tutorial · JavaScript
Lexical scoping means that the scope of a variable is determined by its position in the
source code. Inner functions have access to variables declared in their outer scope.
Example:
function outer() {
let name = "Sandeep";
function inner() {
console.log(name); // accesses outer variable
inner();
outer(); // Sandeep
🔹 4. Objects and Arrays – Q&A
JavaScript JavaScript Tutorial · JavaScript
Using try...catch...finally or Promise .catch().
Example:
try {
throw new Error("Something went wrong!");
} catch (err) {
console.error(err.message);
} finally {
console.log("Cleanup code");
Intermediate
JavaScript JavaScript Tutorial · JavaScript
Reboot is a modernized CSS reset that standardizes browser styles for consistent
rendering.
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
An object is a collection of key-value pairs used to store related data and functions.
Example:
let person = { name: "Sandeep", age: 30 };
JavaScript JavaScript Tutorial · JavaScript
Reusable SCSS functions that generate CSS dynamically.
Example:
@include border-radius(10px);
JavaScript JavaScript Tutorial · JavaScript
Example:
let car = { brand: "Tesla", model: "Model 3" };
let car2 = new Object();
car2.brand = "BMW";
JavaScript JavaScript Tutorial · JavaScript
Functions defined inside objects are called methods.
Example:
let person = {
name: "Sandeep",
greet() { console.log(`Hello, ${this.name}`); }
person.greet(); // Hello, Sandeep
JavaScript JavaScript Tutorial · JavaScript
Wrap the table in .table-responsive:
<div class="table-responsive">
<table class="table">...</table>
</div>
JavaScript JavaScript Tutorial · JavaScript
this refers to the context in which a function is called.
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Follow me on LinkedIn:
JavaScript JavaScript Tutorial · JavaScript
Example:
const obj = {
name: "Sandeep",
arrow: () => console.log(this.name), // undefined in global
regular() { console.log(this.name); } // Sandeep
obj.regular();
obj.arrow();
JavaScript JavaScript Tutorial · JavaScript
Extract values from objects into variables.
Example:
const person = { name: "Sandeep", age: 30 };
const { name, age } = person;
console.log(name, age); // Sandeep 30
JavaScript JavaScript Tutorial · JavaScript
Arrays are ordered collections of values.
Example:
let numbers = [1, 2, 3, 4];
JavaScript JavaScript Tutorial · JavaScript
Example:
numbers.forEach(n => console.log(n));
JavaScript JavaScript Tutorial · JavaScript
Extract elements from arrays into variables.
Example:
let [first, second] = [10, 20];
console.log(first, second); // 10 20
JavaScript JavaScript Tutorial · JavaScript
JavaScript objects inherit properties and methods from other objects through
prototypes. This allows reuse of methods and shared behavior.
Example:
const parent = { greet() { console.log("Hello"); } };
const child = Object.create(parent);
child.greet(); // Hello
JavaScript JavaScript Tutorial · JavaScript
The prototype chain is the chain of objects that JavaScript follows to look up properties
or methods.
continues up the chain.
Example:
console.log(child.toString()); // from Object.prototype
JavaScript JavaScript Tutorial · JavaScript
or classes (ES6).
Example using constructor:
function Person(name) { this.name = name; }
Person.prototype.greet = function() { console.log(`Hello
${this.name}`); };
const p = new Person("Sandeep");
p.greet(); // Hello Sandeep
JavaScript JavaScript Tutorial · JavaScript
Creates a new object with the specified prototype object.
Example:
const parent = { greet() { console.log("Hello"); } };
const child = Object.create(parent);
child.greet(); // Hello
JavaScript JavaScript Tutorial · JavaScript
Property Description
prototy
A property of functions, used when creating objects with new.
__proto
A property of objects, points to the object’s prototype (used in the prototype
chain).
Example:
function Person() {}
console.log(Person.prototype); // prototype object
const p = new Person();
console.log(p.__proto__); // same as Person.prototype
🔹 6. Classes (ES6+) – Q&A
JavaScript JavaScript Tutorial · JavaScript
Classes are blueprints for creating objects. They provide syntactic sugar over the
traditional prototype-based inheritance.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
const sandeep = new Person("Sandeep", 30);
console.log(sandeep.name); // Sandeep
JavaScript JavaScript Tutorial · JavaScript
The constructor is a special method for initializing new objects created from a class.
Example:
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
JavaScript JavaScript Tutorial · JavaScript
Feature Function Constructor Class
Syntax function Person(){} class Person{}
Hoisting Yes, function declarations are
hoisted
No, classes are not
hoisted
new
required
Recommended Required
JavaScript JavaScript Tutorial · JavaScript
Classes support extends to create a subclass that inherits properties and methods from a
parent class.
Example:
class Animal {
speak() { console.log("Animal speaks"); }
class Dog extends Animal {
speak() { console.log("Dog barks"); }
const dog = new Dog();
dog.speak(); // Dog barks
JavaScript JavaScript Tutorial · JavaScript
super() calls the parent class constructor. Must be called before using this in
subclass.
Example:
class Animal {
constructor(name) { this.name = name; }
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
JavaScript JavaScript Tutorial · JavaScript
Static methods are called on the class itself, not on instances.
Example:
class MathUtils {
static square(x) { return x * x; }
console.log(MathUtils.square(5)); // 25
JavaScript JavaScript Tutorial · JavaScript
Yes, getters and setters control access to object properties.
Example:
class Person {
constructor(name) { this._name = name; }
get name() { return this._name; }
set name(value) { this._name = value; }
const p = new Person("Sandeep");
console.log(p.name); // Sandeep
p.name = "Ravi";
console.log(p.name); // Ravi
🔹 7. Asynchronous JavaScript – Q&A
JavaScript JavaScript Tutorial · JavaScript
Allows non-blocking execution, letting other code run while waiting
for tasks (e.g., network requests).
JavaScript JavaScript Tutorial · JavaScript
Nested callbacks causing hard-to-read code.
Solution: Use Promises or async/await.
JavaScript JavaScript Tutorial · JavaScript
An object representing future completion or failure of an async
task.
JavaScript JavaScript Tutorial · JavaScript
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
JavaScript JavaScript Tutorial · JavaScript
Syntactic sugar over Promises for cleaner asynchronous code.
async function fetchData() {
try {
const res = await fetch('/api/data');
const data = await res.json();
console.log(data);
} catch (err) { console.error(err); }
JavaScript JavaScript Tutorial · JavaScript
JavaScript JavaScript Tutorial · JavaScript
Mechanism that manages async callbacks and executes them after the
call stack is empty.
JavaScript JavaScript Tutorial · JavaScript
🔹 8. Events & Event Handling – Q&A
JavaScript JavaScript Tutorial · JavaScript
button.addEventListener('click', () => console.log('Clicked!'));
JavaScript JavaScript Tutorial · JavaScript
Attach a listener to a parent to handle events on child elements.
JavaScript JavaScript Tutorial · JavaScript
🔹 9. Error Handling – Q&A
JavaScript JavaScript Tutorial · JavaScript
Catching and managing runtime errors to prevent app crashes.
JavaScript JavaScript Tutorial · JavaScript
Blocks to handle exceptions.
try { JSON.parse("invalid"); } catch(e) { console.error(e); }
JavaScript JavaScript Tutorial · JavaScript
class ValidationError extends Error { }
throw new ValidationError("Invalid input");
JavaScript JavaScript Tutorial · JavaScript
URIError
🔹 10. ECMAScript Features (ES6+)
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
let arr2 = [...arr1,4,5]; function sum(...nums){}
JavaScript JavaScript Tutorial · JavaScript
function greet(name="Guest"){console.log(name);}
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
Review the concept and prepare a concise verbal explanation with a real project example.
JavaScript JavaScript Tutorial · JavaScript
?, ?. (ES11)
🔹 76. includes() method for arrays (ES7)
Checks if an array contains a specific element and returns true or
false.
const fruits = ["apple", "banana", "mango"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grapes")); // false
🔹 77. Exponentiation operator ** (ES7)
Raises the left operand to the power of the right operand.
console.log(2 ** 3); // 8
console.log(5 ** 2); // 25
🔹 78. async/await (ES8)
Definition: Syntactic sugar over Promises to write asynchronous code
like synchronous code.
Example:
async function fetchData() {
try {
const response = await fetch("
const data = await response.json();
console.log(data);
} catch (err) {
console.error(err);
fetchData();
Notes:
Promise.
rejects.
🔹 79. Object.entries() and Object.values() (ES8)
Object.entries(obj) – Returns an array of [key, value] pairs.
const user = {name: "Sandeep", age: 30};
console.log(Object.entries(user));
// [["name", "Sandeep"], ["age", 30]]
Object.values(obj) – Returns an array of values.
console.log(Object.values(user));
// ["Sandeep", 30]
🔹 80. String.padStart() and String.padEnd() (ES8)
padStart(targetLength, padString) – Pads the start of a string to
reach a desired length.
const str = "5";
console.log(str.padStart(3, "0")); // "005"
padEnd(targetLength, padString) – Pads the end of a string.
console.log(str.padEnd(3, "*")); // "5**"
🔹 81. Rest/Spread for objects (ES9)
Rest operator {...rest} collects remaining properties into a new object.
Spread operator {...obj} copies properties from one object to another.
Example – Rest:
const {a, b, ...rest} = {a:1, b:2, c:3, d:4};
console.log(rest); // {c: 3, d: 4}
Example – Spread:
const obj1 = {x:1, y:2};
const obj2 = {...obj1, z:3};
console.log(obj2); // {x:1, y:2, z:3}
🔹 82. Promise.finally() (ES9)
Runs a callback after a Promise is settled, regardless of success or failure.
Example:
fetch('/api/data')
.then(res => res.json())
.catch(err => console.error(err))
.finally(() => console.log('Fetch attempt finished'));
🔹 83. Asynchronous iterators (ES9)
Allow iterating over asynchronous data streams using for await...of.
Example:
async function* asyncGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
(async () => {
for await (const num of asyncGenerator()) {
console.log(num);
})();
// Output: 1, 2, 3
🔹 84. Array.flat() and Array.flatMap() (ES10)
Array.flat(depth) – Flattens nested arrays up to the specified depth.
Example:
const arr = [1, [2, [3, 4]]];
console.log(arr.flat(1)); // [1, 2, [3, 4]]
console.log(arr.flat(2)); // [1, 2, 3, 4]
Array.flatMap() – Maps each element and flattens the result by one level.
Example:
const arr = [1, 2, 3];
const result = arr.flatMap(x => [x, x*2]);
console.log(result); // [1, 2, 2, 4, 3, 6]
🔹 85. Object.fromEntries() (ES10)
Converts an array of key-value pairs into an object.
Example:
const entries = [['name', 'Sandeep'], ['age', 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // {name: "Sandeep", age: 30}
🔹 86. Optional catch binding (ES10)
Allows omitting the error parameter in catch if it’s not needed.
Example:
try {
throw new Error("Oops");
} catch {
console.log("Error handled without using the error object");
🔹 87. BigInt (ES11 / 2020)
Represents integers larger than Number.MAX_SAFE_INTEGER.
Example:
const bigNumber = 123456789012345678901234567890n;
console.log(bigNumber + 1n); // 123456789012345678901234567891n
Notes:
🔹 88. Nullish coalescing operator ?? (ES11 / 2020)
Returns the right-hand side value only if the left-hand side is null or undefined.
Example:
const name = null;
console.log(name ?? "Default Name"); // "Default Name"
const age = 0;
console.log(age ?? 18); // 0 (not null or undefined)
🔹 89. Optional chaining ?. (ES11 / 2020)
Safely accesses nested object properties without throwing an error if a property is null or
undefined.
Example:
const user = { profile: { name: "Sandeep" } };
console.log(user.profile?.name); // "Sandeep"
console.log(user.address?.city); // undefined (no error)
🔹 90. Promise.allSettled() (ES11 / 2020)
Waits for all promises to settle (fulfilled or rejected) and returns an array of their results.
Example:
const promises = [Promise.resolve(1), Promise.reject("Error")];
Promise.allSettled(promises).then(results => console.log(results));
// [
// { status: "fulfilled", value: 1 },
// { status: "rejected", reason: "Error" }
// ]
🔹 91. replaceAll() for strings (ES12 / 2021)
Replaces all occurrences of a substring in a string.
Example:
const text = "JavaScript is fun. JavaScript is powerful.";
console.log(text.replaceAll("JavaScript", "JS"));
// "JS is fun. JS is powerful."
Note: Unlike replace(), replaceAll() replaces every match, not just the first.
🔹 92. Promise.any() (ES12 / 2021)
Returns the first fulfilled promise. Rejects only if all promises are rejected.
Example:
const promises = [
Promise.reject("Error1"),
Promise.resolve(42),
Promise.resolve(100)
Promise.any(promises).then(result => console.log(result)); // 42
🔹 93. Logical assignment operators (ES12 / 2021)
Combine logical operations with assignment: &&=, ||=, ??=.
Examples:
let a = true;
let b = false;
// AND assignment
a &&= false;
console.log(a); // false
// OR assignment
b ||= true;
console.log(b); // true
// Nullish assignment
let c = null;
c ??= 10;
console.log(c); // 10
🔹 94. at() method for arrays and strings (ES13 / 2022)
Returns the element at a specific index, supporting negative indexing.
Example – Array:
const arr = [10, 20, 30, 40];
console.log(arr.at(1)); // 20
console.log(arr.at(-1)); // 40 (last element)
Example – String:
const str = "JavaScript";
console.log(str.at(0)); // "J"
console.log(str.at(-3)); // "i"
🔹 95. Top-level await (ES13 / 2022)
Allows using await outside async functions in modules.
Example:
// In a module (ESM)
const data = await fetch("
.then(res => res.json());
console.log(data);
Notes:
🔹 96. Object.hasOwn() (ES13 / 2022)
Checks whether an object has a specific own property (safer than hasOwnProperty).
Example:
const obj = { name: "Sandeep" };
console.log(Object.hasOwn(obj, "name")); // true
console.log(Object.hasOwn(obj, "age")); // false
Advantage:
🔹 97. Array.findLast() and Array.findLastIndex() (ES14+ /
2023+)
testing function.
Example – findLast():
const arr = [1, 2, 3, 4, 5, 6];
const lastEven = arr.findLast(x => x % 2 === 0);
console.log(lastEven); // 6
Example – findLastIndex():
const arr = [1, 2, 3, 4, 5, 6];
const lastEvenIndex = arr.findLastIndex(x => x % 2 === 0);
console.log(lastEvenIndex); // 5
🔹 98. New built-in methods introduced recently (ES14+ / 2023+)
Some useful new methods in modern JavaScript:
Array.toSorted() – Returns a sorted copy of the array without mutating the original.
const arr = [3, 1, 2];
const sortedArr = arr.toSorted();
console.log(sortedArr); // [1, 2, 3]
console.log(arr); // [3, 1, 2]
or replaced.
Note: These methods preserve immutability, unlike their older counterparts like sort()
and reverse().
🔹 99. What is the DOM?
The Document Object Model (DOM) is a programmatic representation of a webpage,
allowing JavaScript to read, manipulate, and modify HTML and CSS.
Example:
console.log(document.body); // Accesses the <body> element
🔹 100. Difference between innerHTML, innerText, and textContent
Example:
const div = document.querySelector("#myDiv");
div.innerHTML = "<p>Hello</p>"; // Inserts <p>Hello</p>
div.innerText = "<p>Hello</p>"; // Displays "<p>Hello</p>"
div.textContent = "<p>Hello</p>"; // Displays "<p>Hello</p>"
🔹 101. How do you select DOM elements?
Use selectors like:
document.getElementById("id")
document.getElementsByClassName("className")
document.getElementsByTagName("tagName")
document.querySelector(".className")
document.querySelectorAll("div p")
🔹 102. Difference between getElementById and querySelector
etc.).
Example:
const el1 = document.getElementById("myDiv");
const el2 = document.querySelector("#myDiv"); // Same result
🔹 103. How do you create and append DOM elements?
const div = document.createElement("div");
div.textContent = "Hello World";
document.body.appendChild(div); // Adds the div to body
🔹 104. How do you update styles using JavaScript?
const div = document.querySelector("#myDiv");
div.style.backgroundColor = "lightblue";
div.style.fontSize = "20px";
🔹 105. What is addEventListener?
Attaches event listeners to DOM elements without overwriting existing ones.
Example:
const button = document.querySelector("#myButton");
button.addEventListener("click", () => {
alert("Button clicked!");
});
🔹 106. What is localStorage?
localStorage allows you to store key-value pairs in the browser that persist even
after the browser is closed.
Example:
localStorage.setItem("username", "Sandeep");
console.log(localStorage.getItem("username")); // "Sandeep"
🔹 107. What is sessionStorage?
sessionStorage stores key-value pairs for the duration of a page session. Data is
cleared when the tab or browser is closed.
Example:
sessionStorage.setItem("token", "abc123");
console.log(sessionStorage.getItem("token")); // "abc123"
🔹 108. Difference between localStorage and sessionStorage
Feature localStorage sessionStorage
Lifetime Persist after browser closes Cleared on tab/browser close
Storage limit ~5-10 MB ~5 MB
Scope Shared across tabs of the same
origin
Only available in the current tab
🔹 109. How do cookies work in JavaScript?
Cookies are small pieces of data stored in the browser and sent to the server with each
request.
Example:
// Set a cookie
document.cookie = "username=Sandeep; expires=Fri, 31 Dec 2025
23:59:59 GMT; path=/";
// Read cookies
console.log(document.cookie);
🔹 110. Difference between cookies and localStorage
Feature Cookies localStorage
Sent to
server?
Yes, with every HTTP request No, only client-side
Storage size ~4 KB ~5-10 MB
Expiry Can have expiration date Persistent until explicitly removed
Accessibility Both client & server Client only
🔹 111. What is the BOM (Browser Object Model)?
The Browser Object Model represents the browser’s window and environment, allowing
JavaScript to interact with the browser itself (not the page content).
Example:
console.log(window.innerWidth); // Width of browser window
console.log(window.navigator.userAgent); // Browser info
🔹 112. Difference between window and document
timers, and document.
Example:
console.log(window.location.href); // Current URL
console.log(document.title); // Page title
🔹 113. How do you use navigator and location objects?
console.log(navigator.userAgent);
console.log(navigator.language);
console.log(location.href); // Full URL
location.href = "
// Redirects page
🔹 114. What is setTimeout() and setInterval()?
setTimeout(() => console.log("Hello after 2s"), 2000);
setInterval(() => console.log("Repeating every 1s"), 1000);
🔹 115. How do you detect browser features?
Feature detection ensures code runs only if a feature is supported.
if ('geolocation' in navigator) {
console.log("Geolocation is supported!");
} else {
console.log("Geolocation not supported");
🔹 116. What is a JavaScript module?
A module is a file that encapsulates code (variables, functions, classes) and exports it so
it can be imported into other files, promoting modularity and reusability.
Example (module.js):
export const pi = 3.14;
export function area(radius) {
return pi * radius * radius;
Usage (main.js):
import { pi, area } from './module.js';
console.log(area(5)); // 78.5
🔹 117. What are named vs default exports?
export const x = 10;
export const y = 20;
// Import
import { x, y } from './module.js';
export default function greet() { console.log("Hello!"); }
// Import
import greetFunc from './module.js';
greetFunc(); // Hello!
🔹 118. How do ES6 modules differ from CommonJS?
Feature ES6 Modules CommonJS
Syntax import / export require / module.exports
Loading Static (compile-time) Dynamic (runtime)
Browser support Native in modern browsers Needs bundler (Webpack,
Node.js)
Tree shaking Supported Not supported
🔹 119. What is tree shaking?
Tree shaking is a technique to remove unused code from a module during bundling,
reducing file size.
Example:
// utils.js
export function usedFunc() { return 1; }
export function unusedFunc() { return 2; }
// Only import usedFunc
import { usedFunc } from './utils.js';
Bundler removes unusedFunc from the final bundle.
🔹 120. What is a memory leak in JavaScript?
A memory leak occurs when memory that is no longer needed is not released, leading
to increased memory usage and potential slowdowns.
Example:
let arr = [];
function addToArray() {
arr.push(new Array(1000000).fill('*')); // Keeps adding large
arrays
Memory keeps growing because references are not cleared.
🔹 121. How can you avoid memory leaks?
🔹 122. What is debouncing and throttling?
call. Useful for input events.
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
for scroll or resize events.
function throttle(func, limit) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(this, args);
🔹 123. What is garbage collection?
Garbage collection is the automatic process of freeing memory that is no longer
referenced, handled by the JavaScript engine (e.g., V8).
Example:
let obj = { name: "Sandeep" };
obj = null; // Previous object is now eligible for garbage
collection
🔹 124. What is event loop starvation?
Event loop starvation occurs when long-running synchronous code blocks the event
loop, preventing other tasks (like UI updates or async callbacks) from executing.
Example:
while(true) {} // Infinite loop blocks everything
🔹 125. What are best practices for writing efficient JavaScript?
🔹 126. What is functional programming?
Functional programming (FP) is a programming paradigm where functions are treated as
first-class citizens and focus on pure functions, immutability, and avoiding side effects.
Example:
const add = (a, b) => a + b; // Pure function
🔹 127. What is immutability?
Immutability means data cannot be changed after it is created. Instead, new objects or
arrays are returned when updates are needed.
Example:
const arr = [1, 2, 3];
const newArr = [...arr, 4]; // Original arr remains unchanged
🔹 128. What are map(), filter(), and reduce()?
[1,2,3].map(x => x*2); // [2,4,6]
[1,2,3].filter(x => x>1); // [2,3]
[1,2,3].reduce((sum, x) => sum+x, 0); // 6
🔹 129. What is function composition?
Function composition combines multiple functions into a single function, passing the
output of one as input to the next.
Example:
const double = x => x*2;
const increment = x => x+1;
const compose = (f, g) => x => f(g(x));
compose(double, increment)(3); // (3+1)*2 = 8
🔹 130. What is currying?
Currying transforms a function that takes multiple arguments into a sequence of functions
each taking a single argument.
Example:
const add = a => b => a + b;
add(2)(3); // 5
🔹 131. What is partial application?
Partial application pre-fills some arguments of a function to create a new function.
Example:
const multiply = (a, b) => a * b;
const double = multiply.bind(null, 2);
double(5); // 10
🔹 132. What is a pure function?
A pure function always returns the same output for the same input and has no side
effects.
Example:
const square = x => x*x; // Pure
🔹 133. What is referential transparency?
Referential transparency means an expression can be replaced by its value without
changing the program behavior.
Example:
const x = 10;
console.log(x + 5); // Can replace x with 10 directly
🔹 134. What is the difference between null and undefined?
let a; // undefined
let b = null; // explicitly no value
🔹 135. What is NaN?
NaN stands for Not-a-Number, representing an invalid numeric operation.
console.log("abc" * 2); // NaN
🔹 136. What is eval() and why is it dangerous?
eval() executes a string as JavaScript code. It is dangerous because it can execute
malicious code and cause security vulnerabilities.
eval("2 + 3"); // 5
🔹 137. What is strict mode ("use strict")?
Strict mode enables stricter parsing and error handling in JavaScript, preventing unsafe
actions like creating global variables accidentally.
"use strict";
x = 5; // Error: x is not defined
🔹 138. What is a Symbol?
Symbols are unique and immutable primitive values, often used as object property
keys.
const sym = Symbol('id');
const obj = { [sym]: 123 };
🔹 139. What is a generator function?
Generator functions use function* and can yield multiple values over time, allowing
lazy evaluation.
function* gen() {
yield 1;
yield 2;
const g = gen();
console.log(g.next().value); // 1
🔹 140. What is a WeakMap and WeakSet?
let wm = new WeakMap();
wm.set({}, 'value'); // Key can be garbage collected
🔹 141. What is tail call optimization?
Tail call optimization allows recursive functions to reuse stack frames if the recursive
call is the last operation.
function factorial(n, acc = 1) {
if (n === 0) return acc;
return factorial(n - 1, n * acc); // Tail call
🔹 142. Difference between deep copy and shallow copy?
referenced.
const obj = { a: 1, b: { c: 2 } };
const shallow = { ...obj };
const deep = JSON.parse(JSON.stringify(obj));
🔹 143. What is JSON and how do you parse/serialize it?
const obj = { name: "John" };
const str = JSON.stringify(obj); // serialize
const parsed = JSON.parse(str); // parse
🔹 144. What are template literals?
Template literals allow embedded expressions using backticks `.
const name = "John";
console.log(`Hello ${name}`); // Hello John
🔹 145. Difference between synchronous and asynchronous code?
🔹 146. What are modules and why are they useful?
Modules allow splitting code into reusable files and encapsulation, improving
maintainability.
// math.js
export const add = (a,b) => a+b;
// main.js
import { add } from './math.js';
🔹 147. What is transpilation (Babel, TypeScript)?
Transpilation converts modern JS/TypeScript code into older JavaScript compatible with
older browsers.
🔹 148. What is Type Coercion in JavaScript?
Type coercion is the automatic conversion between types.
console.log('5' - 2); // 3 (string -> number)
🔹 149. How do you detect if a variable is an array?
Array.isArray([1,2,3]); // true
🔹 150. What are polyfills?
Polyfills implement features in older browsers that don’t support them.
if (!Array.prototype.includes) {
Array.prototype.includes = function(el) {
return this.indexOf(el) !== -1;
🔹 151. How do you prevent global namespace pollution?
(function(){
const x = 10;
})();
🔹 152. What are IIFEs (Immediately Invoked Function Expressions)?
IIFE – A function that runs immediately after definition, often used for scoping.
(function() {
console.log("IIFE executed");
})();