Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

By tech stack (from PDF library)

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.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in JavaScript projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does JavaScript solve?
  • What tools or APIs do you use (Frontend ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

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.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in JavaScript projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does Components solve?
  • What tools or APIs do you use (Frontend ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

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.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in JavaScript projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does State solve?
  • What tools or APIs do you use (Frontend ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

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.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in JavaScript projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does API integration solve?
  • What tools or APIs do you use (Frontend ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

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.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in JavaScript projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does Performance solve?
  • What tools or APIs do you use (Frontend ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • String, Number, Boolean, Undefined, Null, BigInt, Symbol
Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

They are part of the browser’s rendering process when the DOM or styles change.

  • Reflow (Layout): Happens when the structure or geometry of the page changes (like

changing size, position, or adding elements).

→ Expensive operation since it recalculates layout.

Follow me on LinkedIn:

  • Repaint: Happens when visual appearance (like color or background) changes

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • block elements take full width and start on a new line.
  • inline-block behaves like inline (stays in the same line) but allows setting width,

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:

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

.highlight { background: yellow; }

Permalink

JavaScript JavaScript Tutorial · JavaScript

<style>

p { color: blue; }

</style>

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

The browser reads HTML line-by-line and builds a DOM (Document Object Model)

tree.

Permalink

JavaScript JavaScript Tutorial · JavaScript

When a browser loads a webpage, it goes through these main steps:

Permalink

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

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

These are semantic elements that help structure a webpage meaningfully:

  • <section> — Groups related content (like a chapter or topic).

Follow me on LinkedIn:

  • <article> — Represents independent, reusable content (like a blog post).
  • <aside> — Contains side information (like ads or related links).

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.

Permalink

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:

  • Centers elements easily.
  • Handles spacing and alignment dynamically.
  • Makes layouts responsive.

Key Takeaway:

Flexbox simplifies alignment and space distribution in one direction.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

#main { width: 80%; }

Permalink

JavaScript JavaScript Tutorial · JavaScript

✅ Responsive design

✅ Pre-styled components

✅ Cross-browser compatibility

✅ Customizable via variables and themes

✅ Speeds up development

Permalink

JavaScript JavaScript Tutorial · JavaScript

✅ Best Practices:

  • Minimize reflows/repaints by avoiding inline styles or frequent layout changes.
  • Use transform and opacity for animations (GPU-accelerated).
  • Combine and minify CSS files.
  • Use specific selectors, not overly complex ones (div ul li a {...} = costly).
  • Avoid large background images or unnecessary CSS rules.
  • Use modern layout methods (Flexbox/Grid) efficiently.

Key Takeaway:

Efficient CSS = fewer reflows, fewer repaints, and lightweight selectors.

Permalink

JavaScript JavaScript Tutorial · JavaScript

<link rel="stylesheet" href="styles.css">

Permalink

JavaScript JavaScript Tutorial · JavaScript

There are three ways to include CSS:

Inline CSS:

<p style="color: blue;">Hello!</p>

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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>

  • role="switch" defines what the element represents.

Follow me on LinkedIn:

  • aria-checked communicates the state to assistive devices.

Key Takeaway:

ARIA makes dynamic interfaces accessible by adding semantic meaning beyond native

HTML.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

JavaScript has 8 data types:

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Object (includes Arrays, Functions, Dates, etc.)
Permalink

JavaScript JavaScript Tutorial · JavaScript

  • JavaScript is interpreted, runs mainly in browsers.
  • Java is compiled, runs on JVM.
  • Syntax differs, and Java is strongly typed, JS is dynamically typed.
Permalink

JavaScript JavaScript Tutorial · JavaScript

V8 is Google’s open-source JavaScript engine used in Chrome and Node.js.

It:

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Tags define the structure and content (e.g., <p>, <h1>, <div>).
  • Attributes provide additional details about an element (e.g., src, href, alt).

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.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Follow me on LinkedIn:

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Element selector: Targets HTML tags.

p { color: green; }

Permalink

JavaScript JavaScript Tutorial · JavaScript

Use classes for reusable styles, IDs for unique elements.

Permalink

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;

Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

DOM + CSSOM = Render Tree (a visual structure of elements and styles).

Permalink

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.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Garbage collection automatically frees memory that’s no longer referenced.

The V8 engine uses the mark-and-sweep algorithm:

  • “Mark” reachable objects from the root.
  • “Sweep” and delete unreachable ones.

Example:

let user = { name: "John" };

user = null; // eligible for garbage collection

Permalink

JavaScript JavaScript Tutorial · JavaScript

Follow me on LinkedIn:

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

SEO optimization starts with clean, structured, and semantic HTML.

Best practices:

Follow me on LinkedIn:

  • Use meaningful tags (<header>, <article>, <footer>).
  • Add <title>, <meta name="description">, and proper heading hierarchy

(<h1> → <h6>).

  • Use descriptive alt text for images.
  • Ensure mobile-friendly and fast-loading pages.
  • Include internal linking and structured data.

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Variables are containers to store data.

Example: let age = 25;

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • <div> is a block-level element (creates a full-width container).
  • <span> is an inline element (used for styling small text portions).

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.

Permalink

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.

Permalink

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

Permalink

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.

Permalink

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:

Permalink

JavaScript JavaScript Tutorial · JavaScript

✅ Result: lightning-fast execution of JS.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Example:

div {

width: 100px;

padding: 10px;

border: 5px solid black;

margin: 20px;

Key Takeaway:

Total width = content + padding + border + margin.

Permalink

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>

Permalink

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.

Permalink

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:

  • href specifies the link URL.
  • target="_blank" opens it in a new tab.

Key Takeaway:

Always add descriptive link text for accessibility.

Permalink

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.

Permalink

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)

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Functions are blocks of reusable code that perform a specific task.

Example:

function greet(name) {

return `Hello, ${name}`;

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Every HTML element is a box made of:

Permalink

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>

Permalink

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:

Permalink

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

Permalink

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">

  • srcset defines available image files and their widths.
  • sizes tells the browser how much space the image will take on different screens.

Key Takeaway:

srcset + sizes = responsive images that load efficiently across devices.

Permalink

JavaScript JavaScript Tutorial · JavaScript

✅ Common techniques:

  • Use Autoprefixer for vendor prefixes.

Use feature queries:

@supports (display: grid) {

.container { display: grid; }

Provide fallbacks for older browsers:

background: #000;

background: linear-gradient(to right, #000, #333);

  • Test with tools like BrowserStack.

Key Takeaway:

Graceful degradation and progressive enhancement keep CSS cross-browser safe.

Follow me on LinkedIn:

Permalink

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

Permalink

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.

Permalink

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.

Permalink

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

Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Primitive types: stored in stack, immutable (number, string, boolean).
  • Reference types: stored in heap, mutable (object, array, function).
Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • <script> runs JavaScript.
  • <noscript> displays content when JavaScript is disabled or not supported.

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.

Permalink

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:

  • Better screen reader support
  • Improved SEO
  • Easier code maintenance

Key Takeaway:

Semantics = communication between developers, browsers, and accessibility tools.

Follow me on LinkedIn:

Permalink

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:

  • Block = independent component
  • Element = part of a block
  • Modifier = variation/state
Permalink

JavaScript JavaScript Tutorial · JavaScript

Use the grid system and responsive classes:

<div class="col-12 col-md-6 col-lg-4">Responsive column</div>

Permalink

JavaScript JavaScript Tutorial · JavaScript

Template literals allow embedded expressions and multi-line strings using backticks

(`).

Example:

let name = "John";

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

Permalink

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]

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Shallow equality: Compares only top-level properties.
  • Deep equality: Compares nested values recursively.

Example:

{a:1} === {a:1} // false (different refs)

Use libraries like Lodash’s _.isEqual() for deep comparison.

Follow me on LinkedIn:

Permalink

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.

Permalink

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:

Permalink

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"

Permalink

JavaScript JavaScript Tutorial · JavaScript

Web Components are reusable custom elements built with:

Permalink

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.

Permalink

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>

Permalink

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

Permalink

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.

Permalink

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.

Permalink

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

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Specificity determines which rule wins when multiple styles target the same element.

Priority order (lowest → highest):

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Returns the type of a variable.

Example:

typeof "hello"; // "string"

typeof 42; // "number"

Permalink

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]

Permalink

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

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Follow me on LinkedIn:

  • .row → Groups columns and manages horizontal alignment
  • .col → Defines how many columns an element spans
Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • <ol> = Ordered List (numbered)
  • <ul> = Unordered List (bulleted)
  • <dl> = Description List (term–definition pairs)

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.

Permalink

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.

Permalink

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:

Permalink

JavaScript JavaScript Tutorial · JavaScript

Via CDN:

<link

href="

p.min.css" rel="stylesheet">

Or via NPM:

npm install bootstrap

Intermediate

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • id is unique and used for a single element.
  • class can be used for multiple elements.

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • == : Equality operator (converts type before comparing)
  • === : Strict equality (no type conversion, checks type + value)

Example:

5 == '5'; // true

5 === '5'; // false

🔹 2. Functions and Scope – Q&A

Permalink

JavaScript JavaScript Tutorial · JavaScript

Use the W3C HTML Validator to check your markup.

To fix errors:

  • Close all tags properly.
  • Avoid duplicate ids.
  • Ensure attributes are correctly formatted.
  • Use only valid HTML elements.

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Objects store data in key-value pairs.

Example:

const user = { name: "Alice", age: 25 };

console.log(user.name); // Alice

Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • .container: Fixed width, adjusts at each breakpoint.
  • .container-fluid: Always spans 100% width.
Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

const arr1 = [1, 2, 3];

const arr2 = new Array(1, 2, 3);

Permalink

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.

Permalink

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

Permalink

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

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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!"));

Permalink

JavaScript JavaScript Tutorial · JavaScript

Controls what happens when content exceeds the container’s size.

Values:

  • visible (default)
  • hidden
  • scroll
  • auto

Example:

div { overflow: auto; }

Key Takeaway:

overflow: auto adds scrollbars only when needed.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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:

Permalink

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.

Permalink

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

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Both create objects, but:

  • {} is simpler and faster.
  • new Object() is less common and can be overridden.

Example:

const a = {}; // Preferred

const b = new Object(); // Not preferred

Permalink

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:

  • Paint API → Custom background drawing.
  • Layout API → Define custom layout logic.
  • Properties & Values API → Register custom CSS properties.

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Entities display reserved characters (like <, >, &) or symbols not on the keyboard.

Example:

<p>Use &lt;div&gt; for containers and &amp; for ampersands.</p>

Key Takeaway:

Entities prevent HTML from confusing symbols with code.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Functions that:

  • Return the same output for the same input.
  • Have no side effects.

Example:

function add(a, b) {

return a + b; // pure

Permalink

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;

Permalink

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

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • <head> holds metadata (title, styles, scripts).
  • <header> defines the visible top section of the page (logo, navigation, heading).

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.

Permalink

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>

Permalink

JavaScript JavaScript Tutorial · JavaScript

Type Meaning

null Intentional absence of value

undefin

Variable declared but not

assigned

Follow me on LinkedIn:

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

NaN stands for “Not-a-Number”, representing an invalid numeric operation.

Example:

console.log("hello" / 2); // NaN

Permalink

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

  • Avoid hiding content with display: none; if screen readers need it.

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.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Reusable UI blocks like buttons, modals, navbars, forms, alerts, etc., that follow

Bootstrap’s design standards.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Minimize HTML, CSS, and JS files.
  • Use lazy loading for images.
  • Use defer or async for scripts.
  • Compress images and enable caching.
  • Reduce DOM size.

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Static typing: Variable types are known at compile-time (e.g., TypeScript, Java).
  • Dynamic typing: Types are determined at runtime (JavaScript).

Example:

let x = 10; // number

x = "text"; // allowed

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Performance:

  • Iframes load as separate browsing contexts, adding extra network requests and

increasing page load time.

SEO:

  • Content inside iframes isn’t fully indexed by search engines.
  • Links and text inside may not count toward the parent page’s SEO.

Best Practice:

  • Use iframes only when necessary (e.g., embedding maps or videos).
  • Add title attributes for accessibility.

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

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Used to find the type of a variable.

typeof "Hello"; // "string"

typeof 10; // "number"

typeof null; // "object" (bug)

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Block-level elements start on a new line and take full width (e.g., <div>, <p>,

<section>).

  • Inline elements stay within a line (e.g., <span>, <a>, <strong>).

Example:

<div>Block</div>

<span>Inline</span>

Key Takeaway:

Block = structure; Inline = styling or small content.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Call stack: Where function execution happens (synchronous).
  • Task queue: Holds async callbacks (processed after stack is empty).

Example:

console.log("1");

setTimeout(() => console.log("2"), 0);

console.log("3");

// Output: 1, 3, 2

Follow me on LinkedIn:

Permalink

JavaScript JavaScript Tutorial · JavaScript

When an event occurs in a nested element:

  • Bubbling: Event moves upward (child → parent).
  • Capturing: Event moves downward (parent → child).

Example:

element.addEventListener('click', handler, true); // capturing

element.addEventListener('click', handler, false); // bubbling

Permalink

JavaScript JavaScript Tutorial · JavaScript

Images that automatically scale with the parent container using .img-fluid:

<img src="..." class="img-fluid" alt="Responsive image">

Permalink

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.

Permalink

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

Permalink

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

✅ ❌

Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Override variables using SCSS.
  • Use Bootstrap’s Theme Customizer or utility API.
  • Or override styles in a custom CSS file.
Permalink

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

Permalink

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

Permalink

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

Permalink

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

Permalink

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.

Permalink

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() {}

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Define a variable with --name and access it with var().

Example:

:root {

  • -main-color: #007bff;
  • -padding: 10px;

button {

background: var(--main-color);

padding: var(--padding);

Follow me on LinkedIn:

Key Takeaway:

CSS variables make styles dynamic and reusable.

Permalink

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

Permalink

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:

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • <b> only makes text bold visually.
  • <strong> adds semantic meaning (important text).

Example:

<b>Warning:</b> Incorrect password.<br>

<strong>Warning:</strong> Incorrect password.

Key Takeaway:

Use <strong> for emphasis that affects meaning.

Permalink

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>

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • <i> makes text italic for style only.
  • <em> gives emphasis that can change meaning.

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.

Permalink

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:

Permalink

JavaScript JavaScript Tutorial · JavaScript

A function that:

  • Always returns the same output for the same input
  • Has no side effects (doesn’t modify external variables)

Example:

function sum(a, b) {

return a + b;

Permalink

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

Permalink

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.

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Provides consistent button styling:

<button class="btn btn-primary">Click</button>

Permalink

JavaScript JavaScript Tutorial · JavaScript

Styled inputs, selects, and textareas:

<input type="text" class="form-control" placeholder="Enter name">

Permalink

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.

Permalink

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.

Permalink

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

Permalink

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

Permalink

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

Permalink

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

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Mutable: Can be changed after creation (e.g., arrays, objects).
  • Immutable: Cannot be changed once created (e.g., strings, numbers).
Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Parameters: variables listed in the function definition
  • Arguments: actual values passed to the function when calling it

Example:

function greet(name) { // name = parameter

console.log(`Hello ${name}`);

greet("Sandeep"); // "Sandeep" = argument

🔹 3. Closures and Lexical Scope – Q&A

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Prefixes ensure CSS works across browsers before full support.

Example:

Follow me on LinkedIn:

.box {

  • webkit-border-radius: 10px; /* Chrome, Safari */
  • moz-border-radius: 10px; /* Firefox */

border-radius: 10px; /* Standard */

Key Takeaway:

Vendor prefixes provide cross-browser compatibility for experimental features.

Intermediate

Permalink

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?

  • .order-*: Changes element order in flex containers.
  • .offset-*: Adds left margin space in grids.

<div class="col-md-4 order-2 offset-md-1"></div>

Follow me on LinkedIn:

Permalink

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()

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

They provide default values when no argument is passed.

Example:

function greet(name = "Guest") {

return `Hello, ${name}`;

Permalink

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:

Permalink

JavaScript JavaScript Tutorial · JavaScript

The period between variable declaration and initialization where it cannot be accessed.

Example:

console.log(x); // ReferenceError

let x = 10;

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Use a custom CSS file loaded after Bootstrap.
  • Or customize variables via SCSS before compilation.
Permalink

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.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • No own this
  • No arguments object
  • Cannot be used as constructors
  • No super or new.target
Permalink

JavaScript JavaScript Tutorial · JavaScript

Bootstrap 5 uses Flexbox by default for its grid system and utilities (.d-flex,

.justify-content-*, .align-items-*).

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Data privacy / encapsulation
  • Callbacks and event handlers
  • Memoization / caching
  • Module pattern for structuring code

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Method Add

Props

Modify Delete

preventExtensio

ns()

❌ No ✅ Yes ✅ Yes

seal() ❌ No ✅ Yes ❌ No

freeze() ❌ No ❌ No ❌ No

Permalink

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

Permalink

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

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Use margin (m-*) and padding (p-*) utilities:

<div class="p-3 m-2 text-center"></div>

Permalink

JavaScript JavaScript Tutorial · JavaScript

Yes. Variables inside the outer function cannot be accessed directly, only via inner

functions.

Example: See createCounter() above.

Permalink

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)

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Install React-Bootstrap (npm install react-bootstrap bootstrap).
  • Import components:

import { Button } from 'react-bootstrap';

<Button variant="primary">Click</Button>

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Both execute dynamic code, but:

  • eval() executes in the current scope (less safe).
  • Function() executes in a new scope (safer).

Example:

eval("var a = 5");

const b = new Function("return 5;");

⚠ Both are discouraged due to security and performance issues.

Bootstrap Interview Questions

Permalink

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

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Reboot is a modernized CSS reset that standardizes browser styles for consistent

rendering.

Follow me on LinkedIn:

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Reusable SCSS functions that generate CSS dynamically.

Example:

@include border-radius(10px);

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Using object literal: {}
  • Using new Object() constructor

Example:

let car = { brand: "Tesla", model: "Model 3" };

let car2 = new Object();

car2.brand = "BMW";

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Wrap the table in .table-responsive:

<div class="table-responsive">

<table class="table">...</table>

</div>

Permalink

JavaScript JavaScript Tutorial · JavaScript

this refers to the context in which a function is called.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Import only needed components via SCSS.
  • Use tools like PurgeCSS to remove unused classes.
  • Use custom builds from Bootstrap’s build system.
Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Load Bootstrap first, then your custom CSS to override styles.
  • Use namespacing or BEM methodology to prevent conflicts.
  • Combine selectively via SCSS imports.

Follow me on LinkedIn:

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Global function: this = window (browser)
  • Object method: this = the object
  • Arrow function: this = lexical context (inherits from parent scope)

Example:

const obj = {

name: "Sandeep",

arrow: () => console.log(this.name), // undefined in global

regular() { console.log(this.name); } // Sandeep

obj.regular();

obj.arrow();

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Arrays are ordered collections of values.

Example:

let numbers = [1, 2, 3, 4];

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • for loop
  • for...of
  • forEach

Example:

numbers.forEach(n => console.log(n));

Permalink

JavaScript JavaScript Tutorial · JavaScript

Extract elements from arrays into variables.

Example:

let [first, second] = [10, 20];

console.log(first, second); // 10 20

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

The prototype chain is the chain of objects that JavaScript follows to look up properties

or methods.

  • If a property isn’t found on the object itself, JS checks the object's prototype, and

continues up the chain.

Example:

console.log(child.toString()); // from Object.prototype

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Objects inherit from other objects via Object.create(), constructor functions,

or classes (ES6).

  • Methods can be shared via prototypes.

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

Permalink

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

Permalink

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

Permalink

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

Permalink

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;

Permalink

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

Permalink

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

Permalink

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;

Permalink

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

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

Allows non-blocking execution, letting other code run while waiting

for tasks (e.g., network requests).

Permalink

JavaScript JavaScript Tutorial · JavaScript

Nested callbacks causing hard-to-read code.

Solution: Use Promises or async/await.

Permalink

JavaScript JavaScript Tutorial · JavaScript

An object representing future completion or failure of an async

task.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • pending
  • fulfilled
  • rejected
Permalink

JavaScript JavaScript Tutorial · JavaScript

fetch('/api/data')

.then(res => res.json())

.then(data => console.log(data))

.catch(err => console.error(err));

Permalink

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

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Promise.all – waits for all promises to resolve
  • Promise.race – resolves/rejects as soon as one completes
Permalink

JavaScript JavaScript Tutorial · JavaScript

Mechanism that manages async callbacks and executes them after the

call stack is empty.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • Call stack: executes synchronous code
  • Microtask queue: handles Promises
  • Macrotask queue: handles setTimeout, I/O, etc.

🔹 8. Events & Event Handling – Q&A

Permalink

JavaScript JavaScript Tutorial · JavaScript

An action like click, load, input, keypress.

Permalink

JavaScript JavaScript Tutorial · JavaScript

button.addEventListener('click', () => console.log('Clicked!'));

Permalink

JavaScript JavaScript Tutorial · JavaScript

Attach a listener to a parent to handle events on child elements.

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • preventDefault() – stops default browser action
  • stopPropagation() – stops event bubbling

🔹 9. Error Handling – Q&A

Permalink

JavaScript JavaScript Tutorial · JavaScript

Catching and managing runtime errors to prevent app crashes.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Blocks to handle exceptions.

try { JSON.parse("invalid"); } catch(e) { console.error(e); }

Permalink

JavaScript JavaScript Tutorial · JavaScript

Runs always, whether error occurs or not.

Permalink

JavaScript JavaScript Tutorial · JavaScript

class ValidationError extends Error { }

throw new ValidationError("Invalid input");

Permalink

JavaScript JavaScript Tutorial · JavaScript

  • ReferenceError, TypeError, SyntaxError, RangeError, EvalError,

URIError

🔹 10. ECMAScript Features (ES6+)

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

`Hello ${name}`

Permalink

JavaScript JavaScript Tutorial · JavaScript

const [a,b]=[1,2]; const {x,y}={x:10,y:20};

Permalink

JavaScript JavaScript Tutorial · JavaScript

let arr2 = [...arr1,4,5]; function sum(...nums){}

Permalink

JavaScript JavaScript Tutorial · JavaScript

function greet(name="Guest"){console.log(name);}

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

JavaScript JavaScript Tutorial · JavaScript

?, ?. (ES11)

  • replaceAll(), Promise.any() (ES12)
  • at(), top-level await (ES13)
  • Array.findLast(), findLastIndex() (ES14+)

🔹 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:

  • async marks a function as asynchronous and it returns a

Promise.

  • await pauses the function until the Promise resolves or

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:

  • Use n at the end to denote a BigInt literal.
  • Cannot mix Number and BigInt directly in arithmetic.

🔹 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:

  • Works only in modules, not in regular scripts.
  • Makes asynchronous initialization easier.

🔹 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:

  • Works even if hasOwnProperty is overwritten.

🔹 97. Array.findLast() and Array.findLastIndex() (ES14+ /

2023+)

  • findLast() – Returns the last element in the array that satisfies the provided

testing function.

  • findLastIndex() – Returns the index of the last element that satisfies the test.

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.findLast() & Array.findLastIndex() – Already covered.

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]

  • Array.toReversed() – Returns a reversed copy without mutating original.
  • Array.toSpliced() – Returns a copy of the array with spliced elements removed

or replaced.

  • Array.with() – Returns a new array with an element replaced at a given index.
  • String.toSorted(), String.toReversed() – Similar operations for strings.

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

  • innerHTML – Returns/sets HTML content, including tags.
  • innerText – Returns/sets rendered text, respects CSS styles.
  • textContent – Returns/sets all text, ignores CSS, faster than innerText.

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

  • getElementById – Selects an element by its ID, returns one element.
  • querySelector – Selects first matching element by CSS selector (ID, class, tag,

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

  • window – Represents the browser window, contains the BOM, global functions,

timers, and document.

  • document – Represents the HTML page content, part of the DOM.

Example:

console.log(window.location.href); // Current URL

console.log(document.title); // Page title

🔹 113. How do you use navigator and location objects?

  • navigator – Provides browser information.

console.log(navigator.userAgent);

console.log(navigator.language);

  • location – Provides URL info and allows navigation.

console.log(location.href); // Full URL

location.href = "

// Redirects page

🔹 114. What is setTimeout() and setInterval()?

  • setTimeout() – Executes a function once after a delay.

setTimeout(() => console.log("Hello after 2s"), 2000);

  • setInterval() – Executes a function repeatedly at intervals.

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?

  • Named exports – Export multiple things with their names; must import using {}.

export const x = 10;

export const y = 20;

// Import

import { x, y } from './module.js';

  • Default export – Only one export per module; can import with any name.

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?

  • Remove event listeners when not needed.
  • Nullify references to large objects.
  • Avoid global variables.
  • Use WeakMap or WeakSet for temporary storage.
  • Properly manage closures.

🔹 122. What is debouncing and throttling?

  • Debouncing – Ensures a function runs only after a specified delay since the last

call. Useful for input events.

function debounce(func, delay) {

let timer;

return function(...args) {

clearTimeout(timer);

timer = setTimeout(() => func.apply(this, args), delay);

  • Throttling – Ensures a function runs at most once every specified interval, useful

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?

  • Minimize DOM manipulations.
  • Use event delegation.
  • Avoid global variables.
  • Use debounce/throttle for frequent events.
  • Leverage ES6+ features for clean and performant code.
  • Use let/const instead of var.
  • Optimize loops and array methods.

🔹 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()?

  • map() – Creates a new array by transforming each element.

[1,2,3].map(x => x*2); // [2,4,6]

  • filter() – Creates a new array with elements that satisfy a condition.

[1,2,3].filter(x => x>1); // [2,3]

  • reduce() – Reduces array to a single value using a reducer function.

[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?

  • null – Explicitly assigned to indicate no value.
  • undefined – Default value for uninitialized variables or missing properties.

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?

  • WeakMap – Object keys are weakly referenced, helps avoid memory leaks.
  • WeakSet – Set of objects with weak references.

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?

  • Shallow copy – Copies top-level properties only, nested objects remain

referenced.

  • Deep copy – Copies entire object structure, no references.

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?

  • JSON – JavaScript Object Notation, a lightweight data interchange format.

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?

  • Synchronous – Executes line by line, blocking further execution.
  • Asynchronous – Executes non-blocking, allows other code to run while waiting.

🔹 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?

  • Use IIFE or modules.
  • Avoid global variables.

(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");

})();

Permalink