Common JavaScript Interview Question 🧠 💡 Scenario: You have an array of users: const users = [ { name: "Mohit", city: "Delhi" }, { name: "Amit", city: "Delhi" }, { name: "Rohit", city: "Noida" } ]; The interviewer asks: “How would you group these users by their city using JavaScript?” 👀 Simple-looking, but it tests: • Mastery of array methods • Understanding of reduce and object manipulation • Problem-solving mindset for real-world data 💡 Tip: Questions like this aren’t about memorizing syntax. They’re about how you think about transforming data efficiently 🚀 #JavaScript #JSInterview #FullStackInterview #CodingInterview #WebDevelopment #MERNStack #ProblemSolving #FrontendDeveloper
Grouping Users by City with JavaScript Array Methods
More Relevant Posts
-
🚨 JavaScript Engine Internals & Performance (Senior Interview Level) 🚨 Framework knowledge gets you shortlisted. Engine knowledge gets you selected. Let’s go 👇 🧠 Question 1: What happens when JavaScript runs your code? JavaScript engine (V8, SpiderMonkey) does: 1️⃣ Parsing → AST (Abstract Syntax Tree) 2️⃣ Compilation → Bytecode 3️⃣ JIT Optimization → Optimized machine code 4️⃣ Execution → Call Stack + Memory Heap 📌 Interview line: “JavaScript is interpreted and JIT-compiled.” 🧠 Question 2: Call Stack vs Memory Heap Call Stack → function execution Memory Heap → object storage 💥 Stack overflow happens due to deep recursion, not memory size. 🧠 Question 3: What is Garbage Collection? JS uses mark-and-sweep algorithm. ✔ Objects reachable → kept ❌ Unreachable → cleaned 📌 Memory leaks happen when references are accidentally retained. 🧠 Question 4: What causes memory leaks in JS? Common real-world reasons: Uncleared setInterval Detached DOM nodes Global variables Closures holding large data Interviewers LOVE practical answers. 🧠 Question 5: Why is JS single-threaded? To avoid: ❌ race conditions ❌ deadlocks Async is handled via: ✔ Event Loop ✔ Callback queues 📌 Mention Web Workers for parallelism. 🧠 Question 6: How does V8 optimize code? Inline caching Hidden classes Function inlining ⚠️ De-optimization happens when: Object shapes change Types change dynamically Senior-level gold 🥇 🧠 Question 7: How to write performant JavaScript? ✔ Avoid unnecessary re-renders ✔ Batch DOM updates ✔ Use debouncing/throttling ✔ Prefer const ✔ Avoid blocking the main thread 🧠 Question 8: What is the critical rendering path? Sequence: HTML → DOM CSS → CSSOM DOM + CSSOM → Render Tree Layout → Paint → Composite 📌 Performance + frontend roles = must know. 💬 Interview Reality You don’t need to know everything. But if you can explain: ✔ How JS runs ✔ How memory is managed ✔ Why performance breaks You’re already in the top 5%. 👇 Comment “PART 6” if you want: • JS system-design interview questions • JavaScript + React performance traps • Real production debugging scenarios • Staff / Lead engineer interview prep #JavaScript #V8 #Performance #InterviewPreparation #Frontend #FullStackDeveloper #ReactJS #NodeJS #LinkedInTech 🚀
To view or add a comment, sign in
-
🚀 JavaScript Interview Roadmap Most developers focus only on: Variables, Arrays, Objects, Promises, Async/Await… But Product Companies and Top MNCs expect much deeper understanding of JavaScript Internals. So I created this complete JavaScript Interview Checklist 👇 ✅ JavaScript Fundamentals - Variables (var / let / const) - Data Types - Type Coercion - Functions - Arrays - Objects ✅ ES6+ Concepts - Arrow Functions - Destructuring - Spread / Rest - Modules - Optional Chaining - Map / Set / WeakMap ✅ Scope & Execution ⭐ Execution Context ⭐ Call Stack ⭐ Lexical Scope ⭐ Scope Chain ⭐ Hoisting ⭐ Temporal Dead Zone ⭐ Closures ⭐ this keyword ✅ Functions Deep Dive - Higher Order Functions - Pure vs Impure Functions - Currying - Memoization - IIFE ✅ Objects & Prototype ⭐ Prototype ⭐ Prototype Chain ⭐ Inheritance - Object.freeze() - Object.seal() - Object.defineProperty() ✅ Async JavaScript ⭐ Callbacks ⭐ Promises ⭐ Promise.all() ⭐ Promise.race() ⭐ Async Await ⭐ Generators ✅ Event Loop Internals ⭐ Microtask Queue ⭐ Callback Queue ⭐ setTimeout vs Promise ✅ Memory Management - Shallow vs Deep Copy - Garbage Collection - Memory Leak ✅ Browser Internals - DOM - Event Bubbling - Event Delegation - Reflow & Repaint ✅ Performance Optimization ⭐ Debouncing ⭐ Throttling ⭐ Lazy Loading ⭐ Code Splitting ⭐ Tree Shaking ✅ Design Patterns - Module Pattern - Singleton Pattern - Observer Pattern - Factory Pattern 📌 Key Takeaway: To move from 5–8 LPA to 20–30+ LPA roles, Understanding "How JavaScript Works Internally" is more important than just writing syntax. 🚀 #javascript #frontenddeveloper #angular #webdevelopment #jobsearch #softwareengineer #learninginpublic #interviewpreparation
To view or add a comment, sign in
-
Day 21/50 – JavaScript Interview Question? Question: What is the difference between slice(), splice(), and split()? Simple Answer: slice() extracts a portion of an array/string without modifying the original. splice() adds/removes elements from an array and modifies it in place. split() converts a string into an array based on a delimiter. 🧠 Why it matters in real projects: These are fundamental array and string manipulation methods used daily. slice() is crucial for immutable updates in React/Redux, splice() for in-place modifications, and split() for parsing CSV data, URLs, or user input. 💡 One common mistake: Using splice() when you need immutability (like in React state updates), which causes unexpected mutations. Also confusing slice() and splice() due to similar names. 📌 Bonus: // slice() - extracts without mutation const arr = [1, 2, 3, 4, 5]; const sliced = arr.slice(1, 3); // [2, 3] console.log(arr); // [1, 2, 3, 4, 5] - unchanged // splice() - modifies original array const arr2 = [1, 2, 3, 4, 5]; const removed = arr2.splice(1, 2, 'a', 'b'); console.log(removed); // [2, 3] console.log(arr2); // [1, 'a', 'b', 4, 5] - changed! // split() - string to array const str = "hello-world-test"; const parts = str.split('-'); // ['hello', 'world', 'test'] // React state update - use slice, not splice! setState(prevArr => [...prevArr.slice(0, index), ...prevArr.slice(index + 1)]); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Arrays #WebDev #Coding
To view or add a comment, sign in
-
🚀 JavaScript Interview Classic: Product of Array Except Self (No Division!) You’re given an array like: [1, 2, 3, 4] 👉 Build a new array where each index contains the product of all numbers except itself: ✅ Output → [24, 12, 8, 6] But here’s the catch 👀 ❌ No division ✅ Must run in O(n) time 🧠 Think in “Left” and “Right” products Instead of multiplying everything again and again, ask: At index i: ➡️ What’s the product of all elements on the left? ⬅️ What’s the product of all elements on the right? Then: answer[i] = leftProduct × rightProduct 🎯 JavaScript Solution (Optimized: O(n) time, O(1) extra space) function productExceptSelf(nums) { const n = nums.length; const result = new Array(n).fill(1); // 1) Build prefix products into result let prefix = 1; for (let i = 0; i < n; i++) { result[i] = prefix; // product of all elements to the left of i prefix *= nums[i]; } // 2) Multiply postfix products into result let postfix = 1; for (let i = n - 1; i >= 0; i--) { result[i] *= postfix; // multiply by product of all elements to the right of i postfix *= nums[i]; } return result; } ✅ Handles zeros correctly ✅ No division ✅ Interview-approved 🧩 Mini Walkthrough (Super Quick) For [1,2,3,4] Prefix pass builds: [1, 1, 2, 6] Postfix pass multiplies: → [24, 12, 8, 6] 🔥 If you want to level up: Can you do it in one loop? 😉 Hint: Two pointers i and j. #DataStructures #Algorithms #JavaScript #CodingInterview #LeetCode #ProblemSolving #WebDevelopment #SoftwareEngineering #Programming #DeveloperCommunity #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 12 Topic: Error Handling in JavaScript (try, catch, finally) Continuing my JavaScript interview revision series, today’s focus was on a very important but often overlooked topic: 👉 Error Handling using try–catch–finally Good developers don’t just write code that works — they write code that handles failures gracefully. 🎪 Real-World Example: Circus Safety Net Imagine a trapeze performance in a circus. 1️⃣ Acrobat attempts a risky trick (TRY). 2️⃣ If something goes wrong, the safety net catches them (CATCH). 3️⃣ After performance, crew resets equipment no matter what (FINALLY). Whether success or failure, cleanup always happens. JavaScript error handling works the same way. 💻 Practical JavaScript Example async function fetchUser() { try { console.log("Fetching user data..."); const response = await fetch("https://lnkd.in/dAktZdHe"); if (!response.ok) { throw new Error("Failed to fetch data"); } const data = await response.json(); console.log("User:", data); } catch (error) { console.error("Something went wrong:", error.message); } finally { console.log("Cleanup: Stop loader / close connection"); } } fetchUser(); Execution Flow ✅ If request succeeds → catch block is skipped ❌ If request fails → catch handles error 🔁 finally runs in both cases ✅ Why Interviewers Ask This Because it tests: • Defensive coding skills • Async error handling understanding • Custom error throwing • Production-ready code thinking 📌 Goal: Share daily JavaScript concepts while preparing for interviews and help others revise fundamentals. Next topics: Event delegation, closures deep dive, execution context, and more. Let’s keep learning in public 🚀 #JavaScript #InterviewPreparation #ErrorHandling #AsyncJavaScript #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
🧠 This is one of the MOST important JavaScript interview traps 👀 (Even developers with 3–5+ years pause here.) No frameworks. No libraries. No tricks. Just core JavaScript behavior. 🧩 Output-Based Question (Destructuring + Function Arguments) const example = ({ a, b, c }) => { console.log(a, b, c); }; example(0, 1, 2); ❓ What will be printed? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. 0 1 2 B. 0 undefined undefined C. undefined undefined undefined D. Throws a TypeError 👇 Drop ONE option only (no explanations yet 👀) ⚠️ Why this question is important Senior interviewers love this pattern because it exposes whether you truly understand: • How destructuring really works • How function parameters are passed • The difference between objects and primitives • What happens when types don’t match expectations Most developers assume: “JavaScript will somehow map the values.” It won’t. When your mental model is wrong: APIs break Config objects fail Production errors appear unexpectedly This isn’t a syntax question. It’s a fundamentals question. Strong JavaScript developers don’t memorize answers. They understand how the engine thinks. 💡 I’ll pin the full breakdown after a few answers. #JavaScript #JSFundamentals #CodingInterview #FrontendDeveloper #FullStackDeveloper #InterviewPrep #DevelopersOfLinkedIn #JSInterviewSeries
To view or add a comment, sign in
-
-
🚀 JavaScript Interview Prep Series — Day 16 Topic: Map, Set & WeakMap in JavaScript Continuing my JavaScript interview revision journey, today I focused on modern JavaScript data structures: 👉 Map, Set, and WeakMap These are powerful alternatives to traditional objects and arrays for managing data efficiently. 🏨 Real-World Example 1️⃣ Map — Hotel Reception System At a hotel reception: Room number acts as a key Guest information is the value Receptionist can quickly fetch guest info using the room number. Similarly, Map stores key-value pairs, and keys can be any data type. 2️⃣ Set — VIP Guest List At a club entrance: Each guest name can appear only once Duplicate entries are rejected Set works the same way — it stores only unique values. 3️⃣ WeakMap — Temporary Visitor Badges Visitors receive temporary badges: Once they leave, badges become invalid automatically System cleans up unused badges WeakMap automatically removes entries when keys (objects) are no longer referenced. 💻 Practical JavaScript Examples Map Example const guestMap = new Map(); guestMap.set("room101", "John"); guestMap.set("room102", "Alice"); console.log(guestMap.get("room101")); console.log(guestMap.size); Set Example const guests = new Set(); guests.add("John"); guests.add("Alice"); guests.add("John"); // ignored console.log(guests); WeakMap Example const cache = new WeakMap(); let user = { name: "Raja" }; cache.set(user, "Session data"); user = null; // automatically cleanes ✅ Why Interviewers Ask This Because it tests: • Knowledge of modern JS features • Efficient data handling • Memory management concepts • Choosing correct data structure 📌 Goal: Share daily JavaScript concepts while revising fundamentals and learning in public. Next topics: WeakSet, Event Delegation, Deep Copy vs Shallow Copy, and more. Let’s keep learning consistently 🚀 #JavaScript #InterviewPreparation #Map #Set #WeakMap #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Day 23/50 – JavaScript Interview Question? Question: What is memoization and how do you implement it? Simple Answer: Memoization is an optimization technique that caches function results based on input arguments. When the function is called again with the same arguments, it returns the cached result instead of recalculating. 🧠 Why it matters in real projects: Memoization dramatically improves performance for expensive computations like recursive Fibonacci, API response parsing, or complex filtering/sorting. React's useMemo and React.memo are built on this principle to prevent unnecessary re-renders. 💡 One common mistake: Over-memoizing everything, which adds memory overhead. Only memoize truly expensive operations. Also, not considering cache size limits, which can cause memory leaks in long-running applications. 📌 Bonus: // Basic memoization implementation function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log('Returning cached result'); return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); return result; }; } // Usage: Expensive calculation const fibonacci = memoize((n) => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }); fibonacci(40); // Calculated once fibonacci(40); // Instant! (from cache) // React example const expensiveComponent = React.memo(({ data }) => { // Only re-renders if data changes }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
DSA Discussion: Add Two Numbers (Linked List) One of the most asked Linked List interview questions: ❓ Problem You are given two non-empty linked lists representing two non-negative integers. Digits are stored in reverse order. Each node contains a single digit. Add the two numbers and return the sum as a linked list. 📌 Example Input: l1 = 2 → 4 → 3 l2 = 5 → 6 → 4 These represent: 342 + 465 Output: 7 → 0 → 8 Because: 342 + 465 = 807 🧠 Approach To solve this: Traverse both linked lists. Add corresponding digits. Keep track of carry. Create a new linked list for result. Use a dummy node to simplify list creation. Key logic: digit = sum % 10 carry = Math.floor(sum / 10) ✅ Clean JavaScript Solution var addTwoNumbers = function(l1, l2) { let dummy = new ListNode(0); let current = dummy; let carry = 0; while (l1 || l2 || carry) { let val1 = l1 ? l1.val : 0; let val2 = l2 ? l2.val : 0; let sum = val1 + val2 + carry; carry = Math.floor(sum / 10); let digit = sum % 10; current.next = new ListNode(digit); current = current.next; if (l1) l1 = l1.next; if (l2) l2 = l2.next; } return dummy.next; }; 🔥 Why Dummy Node? Without dummy node, we would need special handling for the first node. With dummy: Code becomes cleaner No head edge case Easy to return dummy.next 📈 Time & Space Complexity Time Complexity: O(max(n, m)) Space Complexity: O(max(n, m)) Where n and m are lengths of the two linked lists. 🎯 Final Takeaway Most Linked List problems are not about hard logic. They are about handling edge cases smartly. Small tricks like: Using a dummy node Proper carry handling Clean pointer movement make your solution interview-ready. #DSA #LinkedList #CodingInterview #ProblemSolving #JavaScript #DataStructures
To view or add a comment, sign in
-
🚀 **JavaScript: var vs let vs const (Explained Clearly)** If you're learning JavaScript or preparing for interviews, this is a concept you MUST understand 👇 --- ## 🔹 var ```js var name = "Ali"; var name = "Ahmed"; // ✅ Allowed name = "John"; // ✅ Allowed ``` ✔ Function scoped ✔ Can be redeclared ✔ Can be updated ⚠ Problem: Can cause unexpected bugs due to scope issues. --- ## 🔹 let ```js let name = "Ali"; let name = "Ahmed"; // ❌ Error name = "John"; // ✅ Allowed ``` ✔ Block scoped ❌ Cannot be redeclared in same scope ✔ Can be updated ✅ Use when the value needs to change. --- ## 🔹 const ```js const name = "Ali"; name = "Ahmed"; // ❌ Error ``` ✔ Block scoped ❌ Cannot be redeclared ❌ Cannot be reassigned ✅ Use by default in modern JavaScript. --- ## 💡 Best Practice (Modern JS Rule) 👉 Use **const** by default 👉 Use **let** when value needs to change 👉 Avoid **var** --- ### 🎯 Interview Tip Most scope-related bugs happen because of `var`. Understanding block scope vs function scope makes you a stronger developer. --- https://lnkd.in/gzGAbU8A 💬 Quick question: Do you still use `var` in your projects? #JavaScript #FrontendDevelopment #WebDevelopment #Programming #CodingInterview #JSConcepts #SoftwareEngineering #FullStackDeveloper #LearnToCode #DeveloperTips #100DaysOfCode #TechCommunity
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
many approches are there but using map data sturucture also do best way