Day 35/50 – JavaScript Interview Question? Question: What is the new keyword and what happens when you use it? Simple Answer: The new keyword creates an instance of a constructor function or class. It performs four steps: creates an empty object, sets the prototype, binds this to the new object, and returns the object (unless the constructor explicitly returns another object). 🧠 Why it matters in real projects: Understanding new is fundamental to JavaScript's prototypal inheritance and OOP patterns. It's crucial when working with classes, custom data structures, and understanding how frameworks like React create component instances. 💡 One common mistake: Forgetting new when calling a constructor, causing this to refer to the global object (or undefined in strict mode) instead of creating a new instance. Also, not knowing that arrow functions can't be used as constructors. 📌 Bonus: // Constructor function function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; // Using new keyword const alice = new Person('Alice', 30); // What happens behind the scenes: function Person(name, age) { // 1. const this = Object.create(Person.prototype); // 2. this.__proto__ = Person.prototype; this.name = name; // 3. Bind properties to this this.age = age; // 4. return this; (implicit) } // Common mistakes: // ✗ Forgetting new const bob = Person('Bob', 25); // undefined, this = window! console.log(window.name); // "Bob" - polluted global! // ✓ With new const charlie = new Person('Charlie', 35); // ✓ // Arrow functions can't be constructors const PersonArrow = (name) => { this.name = name; }; const dave = new PersonArrow('Dave'); // ✗ TypeError! // ES6 Classes (syntactic sugar over prototypes) class Employee extends Person { constructor(name, age, title) { super(name, age); // Must call before using this this.title = title; } } // Custom return value overrides function Custom() { this.name = 'Test'; return { custom: true }; // This is returned instead } const obj = new Custom(); console.log(obj); // { custom: true } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #OOP #Constructors
JavaScript New Keyword: Understanding Prototypal Inheritance
More Relevant Posts
-
Day 45/50 – JavaScript Interview Question? Question: What is the difference between call(), apply(), and bind()? Simple Answer: All three set the this context explicitly. call(thisArg, arg1, arg2, ...) invokes immediately with individual arguments. apply(thisArg, [args]) invokes immediately with an array of arguments. bind(thisArg) returns a new function with this permanently bound, without invoking. Why it matters in real projects: These methods are essential for method borrowing, event handlers with correct context, React class component methods, and functional programming patterns. Understanding them prevents common this binding bugs and enables powerful composition techniques. One common mistake: Confusing when to use each method. Use call when you know arguments, apply when you have an array, and bind when you need a reusable function with fixed context. Also, forgetting that arrow functions can't have their this rebound. Bonus: const person = { name: 'Alice', greet(greeting, punctuation) { console.log(`${greeting}, ${ this.name }${punctuation}`); } }; const person2 = { name: 'Bob' }; // call() - invoke immediately with individual args person.greet.call(person2, 'Hello', '!'); // "Hello, Bob!" // apply() - invoke immediately with array person.greet.apply(person2, ['Hi', '?']); // "Hi, Bob?" // bind() - return new function (doesn't invoke) const greetBob = person.greet.bind(person2); greetBob('Hey', '.'); // "Hey, Bob." // Practical use cases: // 1. Method borrowing const arrayLike = { 0: 'a', 1: 'b', length: 2 }; const arr = Array.prototype.slice.call(arrayLike); console.log(arr); // ['a', 'b'] // Modern alternative const arr2 = Array.from(arrayLike); // 2. Finding max/min with apply const numbers = [5, 2, 9, 1, 7]; const max = Math.max.apply(null, numbers); // 9 // Modern alternative const max2 = Math.max(...numbers); // 3. Event handlers with correct context class Button { constructor(label) { this.label = label; this.clicks = 0; } handleClick() { this.clicks++; console.log(`${this.label}: ${this.clicks} clicks`); } render() { const btn = document.createElement('button'); // ✗ Wrong - loses context btn.addEventListener('click', this.handleClick); // ✓ Right - preserves context btn.addEventListener('click', this.handleClick.bind(this)); } } // 4. Partial application with bind function multiply(a, b) { return a * b; } const double = multiply.bind(null, 2); console.log(double(5)); // 10 console.log(double(10)); // 20 // 5. Function composition function add(x, y) { return x + y; } const add5 = add.bind(null, 5); const result = [1, 2, 3].map(add5); // [6, 7, 8] // Polyfill for bind (interview favorite) Function.prototype.myBind = function(context, ...args) { const fn = this; return function(...newArgs) { return fn.apply(context, [...args, ...newArgs]); }; }; // Arrow functions can't be rebound const arrowFunc = () => { console.log(this.name); }; const obj = { name: 'Test' }; arrowFunc.call(obj); // Won't bind 'this' to obj!
To view or add a comment, sign in
-
here's some important JavaScript questions to crack interviews 𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗸𝗲𝘆𝘄𝗼𝗿𝗱? - Refers to the object that is currently executing the function - In global scope, this is the window object (in browsers) - Arrow functions do not have their own this 𝟮. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗮𝗹 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲? - JS objects inherit properties and methods from other objects via a prototype chain - Every object has a hidden __proto__ property pointing to its prototype - ES6 class syntax is just cleaner syntax over prototypal inheritance 𝟯. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗦𝗽𝗿𝗲𝗮𝗱 𝗮𝗻𝗱 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 (...)? - Spread expands an array or object: const newArr = [...arr, 4, 5] - Rest collects remaining arguments into an array: function fn(a, ...rest) {} - Same syntax, different context position determines behavior - Great for copying arrays/objects without mutation 𝟰. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴? - Extract values from arrays or objects into variables cleanly - Array: const [first, second] = [1, 2] - Object: const { name, age } = user - Supports default values: const { name = 'Guest' } = user 𝟱. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗘𝘃𝗲𝗻𝘁 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗶𝗼𝗻? - Instead of adding listeners to each child element, add one listener to the parent - Uses event bubbling events travel up the DOM tree - More memory efficient for large lists or dynamic content - Check event.target inside the handler to identify which child was clicked 𝟲. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗰𝗮𝗹𝗹(), 𝗮𝗽𝗽𝗹𝘆()? - All three explicitly set the value of this - call() invokes immediately, passes args one by one - apply() invokes immediately, passes args as an array 𝟳. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗠𝗲𝗺𝗼𝗶𝘇𝗮𝘁𝗶𝗼𝗻? - Caching the result of a function call so it doesn't recompute for the same input - Improves performance for expensive or repeated operations - Commonly implemented using closures and objects/Maps 𝟴. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗛𝗶𝗴𝗵𝗲𝗿-𝗢𝗿𝗱𝗲𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀? - Functions that take other functions as arguments or return them - Examples: .map(), .filter(), .reduce(), .forEach() - Core concept in functional programming with JavaScript 𝟵. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝗮𝗻𝗱 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆? - Shallow copy copies only the top level nested objects are still referenced - Object.assign() and spread {...obj} create shallow copies - Deep copy duplicates everything including nested levels 𝟭𝟬. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗼𝗽𝘁𝗶𝗼𝗻𝗮𝗹 𝗰𝗵𝗮𝗶𝗻𝗶𝗻𝗴 (?.) 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹𝗶𝘀𝗵 𝗰𝗼𝗮𝗹𝗲𝘀𝗰𝗶𝗻𝗴 (??)? - ?. safely accesses nested properties without throwing if something is null/undefined - user?.address?.city returns undefined instead of crashing - ?? returns the right side only if the left is null or undefined Follow the Frontend Circle By Sakshi channel on WhatsApp: https://lnkd.in/gj5dp3fm 𝗙𝗼𝗹𝗹𝗼𝘄𝘀 𝘂𝘀 𝗵𝗲𝗿𝗲 → https://lnkd.in/geqez4re
To view or add a comment, sign in
-
Day 43/50 – JavaScript Interview Question? Question: What is Event Loop, Call Stack, and Task Queue in JavaScript? Simple Answer: The Call Stack tracks function execution (LIFO). The Task Queue (Callback Queue) holds callbacks from async operations. The Event Loop continuously checks if the Call Stack is empty, then moves tasks from the queue to the stack. Microtasks (Promises) have priority over Macrotasks (setTimeout). 🧠 Why it matters in real projects: Understanding the Event Loop is crucial for debugging async behavior, preventing UI blocking, and optimizing performance. It explains why promises execute before setTimeout(0), and helps you write non-blocking code in a single-threaded environment. 💡 One common mistake: Not understanding microtask vs macrotask priority, leading to unexpected execution order. Also, creating infinite microtask loops that starve the macrotask queue and freeze the UI. 📌 Bonus: // Example demonstrating execution order console.log('1: Sync Start'); setTimeout(() => { console.log('2: setTimeout (Macrotask)'); }, 0); Promise.resolve().then(() => { console.log('3: Promise 1 (Microtask)'); }).then(() => { console.log('4: Promise 2 (Microtask)'); }); console.log('5: Sync End'); // Output: // 1: Sync Start // 5: Sync End // 3: Promise 1 (Microtask) // 4: Promise 2 (Microtask) // 2: setTimeout (Macrotask) // Event Loop phases: // 1. Execute all synchronous code // 2. Execute all microtasks (Promises, queueMicrotask) // 3. Execute one macrotask (setTimeout, setInterval, I/O) // 4. Repeat // Call Stack visualization function first() { console.log('First'); second(); console.log('First again'); } function second() { console.log('Second'); third(); } function third() { console.log('Third'); } first(); // Stack: [first] → [first, second] → [first, second, third] // Output: First, Second, Third, First again // Microtask vs Macrotask setTimeout(() => console.log('Macro 1'), 0); Promise.resolve() .then(() => { console.log('Micro 1'); Promise.resolve().then(() => console.log('Micro 2')); }) .then(() => console.log('Micro 3')); setTimeout(() => console.log('Macro 2'), 0); // Output: Micro 1, Micro 2, Micro 3, Macro 1, Macro 2 // All microtasks complete before next macrotask! // Blocking the Event Loop (BAD!) function blockingOperation() { const start = Date.now(); while (Date.now() - start < 3000) { // Blocks for 3 seconds - UI freezes! } } // Better: Break into chunks async function nonBlockingOperation() { for (let i = 0; i < 1000; i++) { // Do work... if (i % 100 === 0) { await new Promise(resolve => setTimeout(resolve, 0)); // Yields to Event Loop every 100 iterations } } } // Microtask starvation (infinite loop) function starveEventLoop() { Promise.resolve().then(() => { starveEventLoop(); // Creates endless microtasks! // Macrotasks never run - UI freezes }); }
To view or add a comment, sign in
-
Day 42/50 – JavaScript Interview Question? Question: What is the Temporal Dead Zone (TDZ) and why does it exist? Simple Answer: The Temporal Dead Zone is the period from entering a scope until a let or const variable is declared. During this time, accessing the variable throws a ReferenceError. It exists to catch errors early and make code more predictable. 🧠 Why it matters in real projects: Understanding TDZ helps debug confusing ReferenceErrors and explains why let/const behave differently from var. It enforces better coding practices by preventing access to uninitialized variables, making bugs more obvious during development rather than in production. 💡 One common mistake: Assuming let and const aren't hoisted because of TDZ. They ARE hoisted, but remain uninitialized in the TDZ. Also, using variables before declaration in complex scopes and getting unexpected ReferenceErrors. 📌 Bonus: // var - no TDZ (hoisted with undefined) console.log(varVariable); // undefined var varVariable = 'Hello'; // let/const - TDZ exists console.log(letVariable); // ReferenceError! let letVariable = 'World'; // TDZ in block scope function example() { // TDZ starts here for 'x' console.log(x); // ReferenceError: Cannot access before initialization let x = 10; // TDZ ends here console.log(x); // 10 } // Tricky TDZ scenario let x = 'outer'; function test() { // TDZ for inner 'x' starts here console.log(x); // ReferenceError! (not 'outer') let x = 'inner'; // TDZ ends } // Why TDZ exists: // 1. Catch errors early function process() { console.log(value); // Intentional? Typo? TDZ makes it obvious! let value = 42; } // 2. Make const meaningful const PI = 3.14159; // Without TDZ, accessing PI before declaration would give undefined // making const less useful // 3. Prevent confusing behavior function confusing() { // What should this print? function getValue() { return value; // 'outer' or ReferenceError? } let value = 'inner'; console.log(getValue()); } // typeof operator gotcha console.log(typeof undeclaredVar); // "undefined" - safe console.log(typeof declaredLater); // ReferenceError! - TDZ let declaredLater = 10; // Best practices: // ✓ Declare variables at the top of their scope function betterCode() { let x, y, z; // Declare first x = getValue(); y = processData(x); z = x + y; } // ✓ Use const by default, let when needed const config = { api: '/api' }; // Won't reassign let counter = 0; // Will change #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #TDZ #ES6 #InterviewPrep #Hoisting
To view or add a comment, sign in
-
🚀 JavaScript Objects – Interview Q&A (Frontend Focused) 1️⃣ What is an object in JavaScript? An object is a collection of key–value pairs used to store structured data. Keys are strings (or symbols), and values can be any data type. 2️⃣ How do you create an object in JavaScript? // Object literal const obj = { name: "JS" }; // Using constructor const obj2 = new Object(); // Using Object.create const obj3 = Object.create(null); 3️⃣ How do you access object properties? obj.name; // Dot notation obj["name"]; // Bracket notation 👉 Bracket notation is useful for dynamic keys. 4️⃣ Difference between dot notation and bracket notation? DotBracketStatic keysDynamic keysFaster & cleanerRequired for special characters 5️⃣ How do you loop through an object? for (let key in obj) { console.log(key, obj[key]); } Object.keys(obj).forEach(key => console.log(key)); 6️⃣ What are Object.keys(), Object.values(), and Object.entries()? Object.keys() → array of keys Object.values() → array of values Object.entries() → array of [key, value] 7️⃣ Are objects mutable in JavaScript? ✅ Yes. Objects are mutable and passed by reference. const a = { x: 1 }; const b = a; b.x = 2; // a.x is also 2 8️⃣ How do you clone an object? // Shallow copy const copy = { ...obj }; const copy2 = Object.assign({}, obj); ⚠️ Nested objects still share references. 9️⃣ Difference between shallow copy and deep copy? Shallow copy → Copies only first level Deep copy → Copies all nested levels const deep = JSON.parse(JSON.stringify(obj)); 🔟 What is this inside an object? this refers to the current object calling the method. const user = { name: "Sweta", greet() { return this.name; } }; 1️⃣1️⃣ What is object destructuring? const { name, role } = user; Used for cleaner code and readability. 1️⃣2️⃣ What is the difference between Object.freeze() and Object.seal()? freeze() → Cannot add, remove, or update properties seal() → Can update existing properties only 1️⃣3️⃣ How do you check if a property exists? "name" in user; user.hasOwnProperty("name"); 1️⃣4️⃣ Real-world use of objects? ✅ API responses ✅ Component props & state ✅ Configuration files ✅ Form handling ✅ State management (Redux / Pinia) 💡 Interview Tip: Strong understanding of objects helps you master immutability, state management, and performance optimization in React & Vue. 👍 Like • 💬 Comment • 🔁 Share if this helped #JavaScript #FrontendInterview #WebDevelopment #React #Vue #CodingInterview #LinkedInLearning
To view or add a comment, sign in
-
Day 47/50 – JavaScript Interview Question? Question: What is the difference between prototype and __proto__? Simple Answer: prototype is a property on constructor functions containing the object used as prototype for new instances. __proto__ is the actual internal link on every object pointing to its prototype. Use Object.getPrototypeOf() instead of __proto__. 🧠 Why it matters in real projects: Understanding the prototype chain explains how JavaScript inheritance works, how methods like .map() are available on arrays, and how classes work under the hood. Essential for creating efficient object hierarchies. 💡 One common mistake: Confusing prototype with __proto__, or modifying Object.prototype which affects all objects globally. Also using deprecated __proto__ instead of standard Object.getPrototypeOf(). 📌 Bonus: // Constructor function function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); // Key difference: console.log(Person.prototype); // Object with greet method console.log(alice.__proto__ === Person.prototype); // true console.log(Object.getPrototypeOf(alice) === Person.prototype); // true // Prototype chain: // alice → Person.prototype → Object.prototype → null // Inheritance example function Employee(name, title) { Person.call(this, name); this.title = title; } Employee.prototype = Object.create(Person.prototype); Employee.prototype.constructor = Employee; const bob = new Employee('Bob', 'Developer'); console.log(bob.greet()); // Inherited from Person // Modern ES6 equivalent class ModernEmployee extends Person { constructor(name, title) { super(name); this.title = title; } } // Best practices: // ✓ Use Object.getPrototypeOf() const proto = Object.getPrototypeOf(alice); // ✗ Don't modify Object.prototype Object.prototype.myMethod = function() {}; // BAD! // ✗ Don't use __proto__ directly (deprecated) // ✓ Use Object.setPrototypeOf() instead #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 36/50 – JavaScript Interview Question? Question: What is async/await and how does it relate to Promises? Simple Answer: async/await is syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code. An async function always returns a Promise, and await pauses execution until a Promise resolves, without blocking the event loop. 🧠 Why it matters in real projects: async/await makes complex asynchronous flows much more readable than Promise chains. It's essential for modern API interactions, database queries, and any sequential async operations. Error handling with try/catch is also more intuitive than .catch(). 💡 One common mistake: Forgetting that await only works inside async functions, or not realizing that await pauses the async function but doesn't block the entire program. Also, using await in loops inefficiently instead of Promise.all(). 📌 Bonus: // Promise chain (harder to read) function getUserPosts() { return fetch('/api/user') .then(res => res.json()) .then(user => fetch(`/api/posts/${user.id}`)) .then(res => res.json()) .then(posts => posts) .catch(error => console.error(error)); } // async/await (cleaner) async function getUserPosts() { try { const userRes = await fetch('/api/user'); const user = await userRes.json(); const postsRes = await fetch(`/api/posts/${user.id}`); const posts = await postsRes.json(); return posts; } catch (error) { console.error(error); throw error; } } // Key concepts: // 1. async function always returns a Promise async function test() { return 'hello'; // Automatically wrapped in Promise } test().then(val => console.log(val)); // "hello" // 2. await pauses the async function, not the program async function demo() { console.log('1'); await delay(1000); console.log('3'); } demo(); console.log('2'); // Prints: 1, 2, 3 // Common mistakes: // ✗ Sequential when parallel is possible (slow) const user = await fetchUser(); const posts = await fetchPosts(); // Waits unnecessarily // ✓ Parallel execution (fast) const [user, posts] = await Promise.all([ fetchUser(), fetchPosts() ]); // ✗ Using await in loops (sequential) for (let id of ids) { await fetchData(id); // Slow! } // ✓ Parallel with Promise.all await Promise.all(ids.map(id => fetchData(id))); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #AsyncAwait #Promises #WebDev #InterviewPrep #ES2017
To view or add a comment, sign in
-
Last week, I shared 20 essential JavaScript interview questions. No textbook definitions. Just clarity. 1️⃣ Higher-Order Functions Functions that take another function as an argument or return one. Examples: map(), filter(), reduce() 👉 Shows strong functional programming fundamentals. 2️⃣ Destructuring Extract values from objects/arrays into variables. Cleaner, shorter, more readable code. 3️⃣ Template Literals Backticks ` ` allow embedding variables using ${}. Used for dynamic strings. 4️⃣ Spread vs Rest Operator Spread → Expands values Rest → Collects values Same syntax (...), different purpose. 5️⃣ Rest vs arguments Rest parameter is a real array. arguments is array-like and outdated. 👉 Prefer rest. 6️⃣ Object vs Array Object → Key-value structure Array → Ordered list Use arrays for lists, objects for structured data. 7️⃣ Cloning Objects/Arrays Use spread (...) for shallow copy. Use structuredClone() for deep copy. 8️⃣ Object.keys / values / entries Used to extract keys, values, or key-value pairs for iteration. 9️⃣ map() Transforms each element and returns a new array. 🔟 map() vs forEach() map() returns a new array. forEach() does not return anything. 👉 Use map() when transforming data. 1️⃣1️⃣ Event Delegation Attach one event listener to a parent instead of multiple children. Improves performance and scalability. 1️⃣2️⃣ JavaScript Modules Split code using export and import. Keeps projects clean and maintainable. 1️⃣3️⃣ Prototype Chain JavaScript uses prototypes for inheritance. Objects inherit properties from other objects. 1️⃣4️⃣ bind vs call vs apply All control this: • call() → arguments individually • apply() → arguments as array • bind() → returns a new function 1️⃣5️⃣ == vs === == allows type coercion. === is strict comparison. 👉 Always prefer ===. 1️⃣6️⃣ DOM The bridge between JavaScript and HTML. Used to read and manipulate webpage elements. 1️⃣7️⃣ preventDefault() & stopPropagation() Control event behavior and event bubbling. 1️⃣8️⃣ Sync vs Async Sync → Runs line by line. Async → Uses callbacks, promises, async/await. 1️⃣9️⃣ Event Object vs Custom Event Event object → Default event data. Custom event → Created manually for specific use cases. 2️⃣0️⃣ Performance Optimization • Debouncing / Throttling • Reduce unnecessary DOM updates • Lazy loading • Efficient loops Candidates don’t fail because they don’t know React. They fail because they can’t clearly explain JavaScript fundamentals. If you can explain these confidently with examples — you're interview ready. Save this. Share with someone preparing for frontend roles. Comment “Advanced JS” if you want the next level questions. #JavaScript #FrontendDeveloper #WebDevelopment #TechCareers #CodingInterview #Mentorship #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 29 Topic: Bundlers & Modules in JavaScript Continuing my JavaScript interview journey, today I revised a very practical frontend concept: 👉 Modules and Bundlers Modern JavaScript apps are built using many small files (modules). Bundlers help package them efficiently for the browser. 🧳 Real-World Example: Packing for a Trip Imagine you're traveling. Before Bundling ❌ You have many small bags: toiletries bag shoe bag electronics bag clothes bag Hard to carry. Messy. Slow. 👉 These are like separate JS modules Bundler at Work ⚙️ A smart packing machine: analyzes items removes duplicates compresses everything organizes efficiently 👉 This is Webpack / Vite / Rollup After Bundling ✅ You get: 🧳 One optimized suitcase 🚀 Easy to carry ⚡ Faster travel 👉 This is bundle.js 💻 Step 1: Create Modules math.js id="x6a7bg" export const add = (a, b) => a + b; export const multiply = (a, b) => a * b; utils.js id="y9k2hf" export const format = (str) => str.trim(); 💻 Step 2: Import in App id="bq9x0u" import { add, multiply } from "./math.js"; import { format } from "./utils.js"; console.log(add(5, 3)); 👉 Code is modular and clean. ⚙️ Step 3: Bundler Magic Bundlers like: Webpack Vite Rollup will: ✅ Merge modules ✅ Remove unused code (tree shaking) ✅ Minify code ✅ Optimize for browser ✅ Reduce HTTP requests 📦 Final Output Id="tju5y3" // bundle.js // One optimized file ready for production This is what browsers typically load in production. 🎯 Why Interviewers Ask This Because it tests: • Modern frontend workflow • Build tool understanding • Performance awareness • Module system knowledge ⚡ When Bundlers Are Important ✔ React / Next.js apps ✔ Large JavaScript projects ✔ Production builds ✔ Performance optimization ✔ Code splitting setups 🧠 Pro Tips ✅ Use ES Modules (import/export) ✅ Prefer Vite for modern projects ✅ Enable tree-shaking ✅ Keep bundles small ✅ Use code splitting when needed 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Code Splitting, Lazy Loading, and advanced performance patterns. Let’s keep the momentum strong 🚀 #JavaScript #InterviewPreparation #Bundlers #Webpack #Vite #Frontend #WebDevelopment #LearningInPublic #Developers
To view or add a comment, sign in
-
-
Day 49/50 – JavaScript Interview Question? Question: What is the difference between stopPropagation(), stopImmediatePropagation(), and preventDefault()? Simple Answer: stopPropagation() prevents event from bubbling/capturing to other elements. stopImmediatePropagation() also prevents other handlers on current element. preventDefault() cancels default browser action but doesn't stop propagation. 🧠 Why it matters in real projects: These control event behavior in complex UIs with nested elements. Misusing them causes bugs like forms not submitting, clicks triggering parent handlers, or custom behavior failing. Critical for proper event handling. 💡 One common mistake: Using stopPropagation() everywhere "to be safe" breaks event delegation patterns. Also confusing preventDefault() with stopping propagation—they serve different purposes. 📌 Bonus: // HTML: <div id="outer"><button id="inner">Click</button></div> const outer = document.getElementById('outer'); const inner = document.getElementById('inner'); // stopPropagation() - stops event flow inner.addEventListener('click', (e) => { console.log('Inner'); e.stopPropagation(); // Stops here! }); outer.addEventListener('click', () => { console.log('Outer'); // Won't fire }); // stopImmediatePropagation() - stops all handlers inner.addEventListener('click', (e) => { console.log('Handler 1'); e.stopImmediatePropagation(); }); inner.addEventListener('click', () => { console.log('Handler 2'); // Won't fire! }); // preventDefault() - cancels default action const link = document.querySelector('a'); link.addEventListener('click', (e) => { e.preventDefault(); // Link won't navigate // Event still propagates to parent! }); const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); // Form won't submit handleAjaxSubmit(new FormData(form)); }); // Practical: Modal overlay modal.addEventListener('click', (e) => { e.stopPropagation(); // Clicks on modal don't close it }); overlay.addEventListener('click', () => { closeModal(); // Clicks on overlay close it }); // Best practice: Don't break delegation document.querySelector('.list').addEventListener('click', (e) => { if (e.target.matches('.item')) { // Don't use stopPropagation here! handleItemClick(e.target); } }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Events #EventPropagation #WebDev #DOM
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development