Day 28/50 – JavaScript Interview Question? Question: What is destructuring in JavaScript? Simple Answer: Destructuring is a syntax that unpacks values from arrays or properties from objects into distinct variables. It provides a concise way to extract multiple values in a single statement. 🧠 Why it matters in real projects: Destructuring makes code cleaner and more readable, especially with React props, API responses, and function parameters. It's ubiquitous in modern JavaScript and reduces boilerplate code significantly. 💡 One common mistake: Trying to destructure null or undefined, which throws an error. Always provide default values or check for existence when destructuring data from APIs or external sources. 📌 Bonus: // Array destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // Object destructuring const user = { name: 'Alice', age: 30, city: 'NYC' }; const { name, age } = user; console.log(name); // "Alice" // Renaming variables const { name: userName, age: userAge } = user; // Default values (prevents undefined) const { country = 'USA' } = user; console.log(country); // "USA" // Nested destructuring const data = { user: { profile: { email: 'a@b.com' } } }; const { user: { profile: { email } } } = data; // React props destructuring function UserCard({ name, age, onDelete }) { return <div>{name}, {age}</div>; } // Function parameters function displayUser({ name, age = 18 }) { console.log(`${name} is ${age}`); } // Common mistake - destructuring undefined const { x } = null; // ✗ TypeError! const { x } = null || {}; // ✓ Safe with fallback #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ES6 #Destructuring #WebDev #InterviewPrep
Destructuring in JavaScript: Extract Values with Ease
More Relevant Posts
-
⚡ Top 14 JavaScript Array Methods Every Developer Should Know If you’re learning JavaScript or preparing for frontend interviews, array methods are used everywhere. Understanding them well can make your code cleaner, shorter, and more efficient. Here are 14 essential JavaScript array methods worth mastering 👇 📌 Core Array Operations .push() ↳ Adds one or more elements to the end of an array. .pop() ↳ Removes the last element from an array. .shift() ↳ Removes the first element from an array. .unshift() ↳ Adds one or more elements to the beginning of an array. 📌 Array Modification & Extraction .slice() ↳ Extracts a portion of an array into a new array. .splice() ↳ Adds, removes, or replaces elements inside an array. 📌 Transformation & Iteration .map() ↳ Creates a new array by transforming each element. .filter() ↳ Creates a new array with elements that match a condition. .reduce() ↳ Reduces the array to a single value using a function. .forEach() ↳ Executes a function on each element (no return value). 📌 Searching & Checking .find() ↳ Returns the first element that matches a condition. .findIndex() ↳ Returns the index of the first matching element. .includes() ↳ Checks if an array contains a specific value. 📌 Sorting .sort() ↳ Sorts the elements of an array in place. 💡 Pro tip: In real-world frontend development, methods like map, filter, and reduce are used heavily in frameworks like React. If this helped, save it for quick revision. #JavaScript #FrontendDevelopment #WebDevelopment #Coding #Programming #ReactJS #TechLearning
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 19 Topic: JavaScript Modules — ESM vs CommonJS Continuing my JavaScript interview preparation journey, today I revised an important modern JS topic: 👉 JavaScript Modules (ESM vs CommonJS) Modules help us organize code, reuse functions, and keep projects maintainable. But in interviews, one common question is: What is the difference between ES Modules and CommonJS? Let’s simplify it. 📚 Real-World Example: Library Borrowing 🟢 ES Modules (Modern Library) Imagine a modern self-service library. You can: Pick only the chapters you need Borrow specific books Load things on demand ✅ Lightweight ✅ Efficient ✅ Future standard This is how ESM imports work. 🟠 CommonJS (Traditional Library) In an old library: You ask for one recipe… But the librarian gives you the entire cookbook set 😅 ❌ Loads whole module ❌ Synchronous ✅ Still widely used in Node.js This is how require() works. 💻 ES Modules Example (Modern) math.js export const add = (a, b) => a + b; export const multiply = (a, b) => a * b; app.js import { add } from "./math.js"; console.log(add(2, 3)); ✅ Static ✅ Tree-shakable ✅ Works in browsers 💻 CommonJS Example (Node.js) math.js const add = (a, b) => a + b; module.exports = { add }; app.js const math = require("./math"); console.log(math.add(2, 3)); 🔥 Key Differences Feature ESM CommonJS Loading Static Runtime ✅ When to Use 👉 Use ESM for modern frontend and new Node projects 👉 Use CommonJS when working with legacy Node codebases 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Event Delegation deep dive, Memory leaks, and more. Let’s keep learning consistently 🚀 #JavaScript #InterviewPreparation #ESModules #CommonJS #NodeJS #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
🧠 Understanding JavaScript Closures Many developers get confused about Closures in JavaScript. Let’s understand it in a simple way 👇 👉 What is Closure? A closure happens when an inner function remembers variables from its outer function — even after the outer function has finished executing. 💡 Simple Line: A function remembers where it was created. 🔎 Example: function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 Even though outer() finished, inner() still remembers count. That memory is called Closure 🔐 🎯 Why Closures are Important? ✅ Data hiding (private variables) ✅ Counters ✅ setTimeout & async logic ✅ Used in React Hooks ✅ Functional programming pattern 🏆 Interview Definition: A closure happens when an inner function remembers variables from its outer function — even after the outer function has finished executing. If you're preparing for frontend interviews, Closures is a MUST-know concept 💪 💬 Question for you: Where have you used closures in real projects? #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #InterviewPreparation
To view or add a comment, sign in
-
-
𝐂𝐨𝐦𝐩𝐥𝐞𝐭𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 (𝟐𝟎𝟐𝟔 𝐔𝐩𝐝𝐚𝐭𝐞𝐝 𝐆𝐮𝐢𝐝𝐞) 🔥 Preparing for JavaScript interviews in 2026? I’ve compiled a practical guide covering beginner to advanced concepts with examples and explanations. This guide includes key topics like: ✔ JavaScript fundamentals ✔ var vs let vs const ✔ Hoisting and scope ✔ Closures and lexical scope ✔ Event loop and asynchronous behavior ✔ Promises and async/await ✔ Debouncing and throttling ✔ Memory management and performance optimization ✔ Node.js related interview concepts JavaScript remains one of the most important languages for modern web development, powering interactive applications in browsers and server environments like Node.js. If you're preparing for interviews or strengthening your fundamentals, this resource will help you revise core concepts with real examples. 🔗 Read the full guide: https://lnkd.in/g7GnWuYE 🔁 Repost to support the community 👉 Follow Tapas Sahoo for more related content 🙏 What’s the most challenging JavaScript interview question you’ve faced? 👇 #JavaScript #WebDevelopment #NodeJS #FrontendDevelopment #CodingInterview #SoftwareEngineering #DeveloperLife #TechCareers #Programming #FullStackDeveloper
To view or add a comment, sign in
-
🚀 Call by Value vs Call by Reference — Every JavaScript Developer Must Understand This One of the most commonly asked interview questions — yet many developers explain it incorrectly. Let’s simplify it 👇 🔹 Call by Value When you pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript copies the value. let a = 10; function update(x) { x = 20; } update(a); console.log(a); // 10 👉 The original variable does NOT change. Because a copy was passed. 🔹 Call by Reference (Not Exactly 😉) When you pass an object, array, or function, JavaScript passes the reference to the memory location. let user = { name: "Sweta" }; function update(obj) { obj.name = "Anita"; } update(user); console.log(user.name); // Anita 👉 The original object changes. Because both variables point to the same memory reference. ⚠️ Important Clarification JavaScript is technically: ✅ Pass by Value But for objects, the value itself is a reference. That’s why many people say “call by reference” — but internally it’s still pass-by-value (of the reference). 🔥 Real Interview Tip If interviewer asks: “Is JavaScript pass by value or pass by reference?” Best answer: JavaScript is pass-by-value. For objects, the value being passed is a reference to the object. 🎯 This shows conceptual clarity. 💡 Why This Matters in Real Projects? Prevents accidental state mutation in React/Vue Helps avoid bugs in Redux/Pinia Essential for understanding immutability Critical when working with micro-frontends & shared state Understanding this deeply makes you a better JavaScript engineer — not just someone who writes syntax. #JavaScript #FrontendDevelopment #ReactJS #VueJS #InterviewPreparation #WebDevelopment
To view or add a comment, sign in
-
⚛️ Top 150 React Interview Questions – 141/150 📌 Topic: ⚡ Babel vs. SWC ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Babel The classic JavaScript transpiler written in JavaScript. It converts modern ES6+ and JSX into backward-compatible JavaScript. SWC (Speedy Web Compiler) A high-performance compiler written in Rust. Designed to replace Babel with extreme speed improvements. Both do the same job → Transpile modern code into browser-compatible code. Difference = Speed + Architecture. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY does SWC matter? 🚀 Velocity SWC can be up to 20x faster (single-core) and up to 70x faster (multi-core). ⚡ Faster HMR Next.js and Vite use SWC for near-instant hot reload. ⏱ Reduced Build Times CI/CD pipelines become significantly faster in large apps. 🧠 Compiled vs Interpreted Babel → JS-based SWC → Rust-compiled (much faster execution) For modern teams → Speed = Productivity. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW does it differ in configuration? You usually don’t configure this manually — frameworks handle it. But structurally: ✅ Babel Configuration (.babelrc) { "presets": ["@babel/preset-react"] } JS-based processing. ✅ SWC Configuration (.swcrc) { "jsc": { "parser": { "syntax": "ecmascript", "jsx": true }, "target": "es2015" } } Rust-powered compilation engine. Same goal. Much faster execution. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE is it used? ⚛️ Next.js (v12+) Uses SWC by default for compilation & minification. ⚡ Vite Ecosystem Uses SWC/esbuild for lightning-fast dev builds. 🏢 Large Applications Where build time directly impacts developer efficiency. 📦 Legacy Codebases Still use Babel for rare plugins not yet supported by SWC. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY Babel is like Hand-Written Translation ✍️ Accurate. Flexible. Reliable. But slower. SWC is like AI Instant Translation 🤖 Same output — finished before you blink. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone optimizing frontend performance #ReactJS #Babel #SWC #WebPerformance #FrontendBuildTools #NextJS #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━
To view or add a comment, sign in
-
-
Day 24/30 – Sort an Array by Function Output in JavaScript Challange🔢 | Custom Comparator 📌 Problem Given: An array arr A function fn Return a new array sortedArr sorted in ascending order based on the value returned by fn(arr[i]). You can assume: fn always returns a number Sorting must be based on fn output 🧠 Example arr = [5, 4, 1, 2, 3] fn = (x) => x * x Since squares are: 25, 16, 1, 4, 9 Sorted by square value: [1, 2, 3, 4, 5] 💡 JavaScript Solution var sortBy = function(arr, fn) { return arr.slice().sort((a, b) => fn(a) - fn(b)); }; 🔎 Why This Works sort() accepts a comparator fn(a) - fn(b) ensures ascending order slice() prevents mutation of the original array Time Complexity: O(n log n) Space Complexity: O(n) (due to copy) ⚡ Real-World Use Cases Sorting users by age Sorting products by price Ranking students by score Sorting tasks by priority 🧠 Interview Insight This pattern is called “sort by projection”: You don’t sort by the element itself — You sort by a derived value. That’s a powerful abstraction concept. #JavaScript #30DaysOfJavaScript #CodingChallenge #JSLogic #ArrayMethods #WebDevelopment #FrontendDevelopment #LearnToCode #CodeEveryday #Programming #DeveloperJourney #TechCommunity #InterviewPrep #LeetCode #AsyncJavaScript #SoftwareEngineering #100DaysOfCode #BuildInPublic Custom comparator JavaScript Sort array by derived value JS JavaScript array sort interview question Higher order functions JavaScript JavaScript sorting techniques JS sort with callback Advanced JavaScript array methods JavaScript coding challenge solution Frontend interview preparation
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop — The Secret Behind Async JavaScript One of the most common questions in JavaScript interviews and real-world debugging is: “Why does JavaScript execute asynchronous code in a specific order?” The answer lies in the JavaScript Event Loop. JavaScript is single-threaded, meaning it can execute only one task at a time. Yet we can run asynchronous operations like API calls, timers, and promises without blocking the main thread. This is possible because of the Event Loop architecture. Let’s break it down 👇 🔹 1. Call Stack (Synchronous Execution) The Call Stack is where JavaScript executes synchronous code line by line. Every function call is pushed onto the stack and removed once executed. 🔹 2. Web APIs (Browser Features) When JavaScript encounters asynchronous operations like: setTimeout() fetch() DOM events They are handed off to Web APIs provided by the browser. 🔹 3. Task Queues There are two important queues: ✅ Microtask Queue (High Priority) Includes: Promise.then() queueMicrotask() MutationObserver These tasks execute immediately after the current call stack is empty. ✅ Macrotask Queue (Lower Priority) Includes: setTimeout() setInterval() DOM events These tasks run only after all microtasks are completed. 🔹 4. The Event Loop The Event Loop continuously checks: 1️⃣ Is the Call Stack empty? 2️⃣ Execute all Microtasks first 3️⃣ Then execute the next Macrotask It repeats this process indefinitely. 💡 Example console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); 👉 Output: 1 4 3 2 Why? 1 and 4 run in the Call Stack Promise.then() goes to the Microtask Queue setTimeout() goes to the Macrotask Queue Microtasks run before macrotasks 📌 Execution Order: Call Stack → Microtasks → Macrotasks 🔥 Key Takeaway Understanding the Event Loop helps you: Debug asynchronous issues Write better non-blocking code Perform well in JavaScript interviews Master frameworks like React, Node.js, and Next.js #JavaScript #WebDevelopment #FrontendDevelopment #AsyncProgramming #EventLoop #Programming #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
🤔 Ever shipped a bug because you thought await makes things run “in parallel”… but two requests still happened one after another? 🧠 JavaScript interview question What is async/await and how is it different from Promises? ✅ Short answer • async/await is syntax on top of Promises (same async model) • async functions always return a Promise • await pauses only that async function, not the whole thread • Error handling becomes normal try/catch instead of .catch() 🔍 The real difference (what interviewers want) Promises are the mechanism. async/await is the cleaner way to write the same thing. But… await can accidentally serialize work: • await inside a loop = often slower (one-by-one) • Starting promises first, then await Promise.all() = parallel (together) 💻 Example: same task, very different performance // ❌ Sequential (one-by-one) async function loadSequential(urls) { const results = []; for (const url of urls) { const res = await fetch(url); results.push(await res.json()); } return results; } // ✅ Parallel (start all, then await together) async function loadParallel(urls) { const promises = urls.map((url) => fetch(url).then((r) => r.json())); return Promise.all(promises); } ⚠️ Common misconceptions • “await blocks the thread” → nope, it yields back to the event loop • “async returns a value” → it returns a Promise of that value • “await replaces Promise.all” → not for parallel work ⚛️ React mini-connection Inside useEffect, you can’t make the callback async, so do this: useEffect(() => { (async () => { const data = await fetch("/api/items").then(r => r.json()); setItems(data); })(); }, []); #javascript #webdevelopment #frontend #reactjs #asyncawait #promises #interviewprep #softwareengineering
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 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