Mutable vs Immutable in JavaScript is one of those concepts that seems simple, but interviewers love to twist it. • Immutable means the value itself cannot be directly modified • Mutable means the value itself can be modified In JavaScript, all primitive types are immutable: String, Number, Boolean, Null, Undefined, Symbol, BigInt So when you do: let a = 10; a = 20; - It may look like 'a' changed, but what actually happens is that a new value is created and the variable is reassigned. - The old value remains untouched and may later be garbage-collected. - This is also why strings behave the way they do. - You can read characters using an index, but you can’t modify them. - Any “change” to a string actually creates a new string behind the scenes. - Strings are not mutable arrays — they’re immutable primitives. let str = "immutable"; str[0] = "i"; // nothing happens Objects are different. Objects are mutable, and arrays are objects in JavaScript: arr[0] = 10 → works arr.push(4) → modifies the same array in memory Here’s an important distinction: • Mutation (same object, same memory) let obj = { x: 1 }; obj.x = 2; • Reassignment (new object, new reference) let obj = { x: 1 }; obj = { x: 2 }; Even with const, this rule stays the same. const obj = { x: 1 }; obj.x = 2; // allowed → mutation obj = { x: 2 }; // error → reassignment not allowed const prevents reassignment, not mutation. You can’t point the variable to a new object, but you can change the existing object’s properties. Because objects are mutable by default, JavaScript gives us: • Object.seal() → cannot add/remove properties, but values can change • Object.freeze() → cannot add, remove, or change anything (also applies to arrays) Takeaway : • Primitives are immutable. Reassignment creates a new value. • Objects and arrays are mutable. Mutation changes the same value in memory. #FrontendDevelopment #JavaScript #JavaScriptInterview #InterviewPrep #WebDevelopment #Mutability
JavaScript Immutable vs Mutable Explained
More Relevant Posts
-
🚀 Top 150 React Interview Questions — 15/150 ⚛️ 🧠 What is JSX? JSX stands for JavaScript XML. It is a syntax extension that lets you write HTML-like code directly inside JavaScript. Instead of complex DOM methods, you can simply write UI in a clean, readable way. ✨ Why we use JSX: ✍️ Easier to write – Much faster than React.createElement() 👀 Visual clarity – Looks like HTML, so UI structure is easy to understand 🧠 Power of JavaScript – Use variables, conditions, loops, and logic inside UI ⚙️ How JSX works behind the scenes: 🌐 Browsers cannot read JSX 🔧 A compiler called Babel converts JSX into plain JavaScript Example: const element = <h1>Hi</h1>; ➡️ Babel converts it to: React.createElement('h1', null, 'Hi'); 📏 Important JSX rules: 1️⃣ Single root element – Wrap everything in one parent (div or <>...</>) 2️⃣ CamelCase attributes – className, onClick, etc. 3️⃣ Closing tags required – <img />, <br /> 4️⃣ JS expressions – Use { } to inject JavaScript 📌 Easy way to remember: JSX is syntactic sugar 🍬 It doesn’t add new power to JavaScript — it just makes UI code cleaner, readable, and declarative. 👇 Comment “React” if this series helps you. #ReactJS #JSX #JavaScript #FrontendDevelopment #ReactInterview #WebDevelopment #LearningInPublic #ReactFundamentals
To view or add a comment, sign in
-
-
#Interview Prep JavaScript array.sort() array.sort() is a JavaScript method used to arrange array elements in a specific order. By providing a compare function, we can control whether the sorting is ascending or descending. Example array Explanation ✅ arr = [6, 2, 4] arr.sort((a, b) => { return a - b; }) How TWO elements are chosen (visual angle) [ 6 , 2 , 4 ] ↑ ↑ a b JS picks neighbor elements a = 6 b = 2 Compare: 6 - 2 = 4 → swap After swap: [ 2 , 6 , 4 ] ▶️ Second pick [ 2 , 6 , 4 ] ↑ ↑ a b Now picks: a = 6 b = 4 Compare: 6 - 4 = 2 → swap After swap: [ 2 , 4 , 6 ] ▶️ Third (check) [ 2 , 4 , 6 ] ↑ ↑ a b Compare: 2 - 4 = -2 → no swap Array stays same ✅ JS always picks TWO values Assigns: first value → a second value → b It compares adjacent elements Moves forward like a sliding window [ a , b ] → compare → swap / no swap → move right 🔄 Same idea for descending arr.sort((a,b) => { return b - a }) [ 6 , 2 , 4 ] ↑ ↑ a b 2 - 6 = -4 → no swap → bigger stays first Result: [ 6 , 4 , 2 ] #JavaScript #Frontend #WebDevelopment #CodingTips #LinkedInLearning #ArrayMethods #Interview
To view or add a comment, sign in
-
🔁 JavaScript Event Loop: Microtasks vs Callback Queue (Explained Clearly) If you want to truly understand asynchronous JavaScript, you must understand how the Event Loop prioritizes tasks. This concept is: ✅ A favorite interview topic ✅ A common source of real-world bugs ✅ Essential for writing predictable, performant JS Let’s break it down 👇 🧩 Two Queues Every JavaScript Developer Should Know 1️⃣ Callback Queue (Macrotasks) Handles: setTimeout setInterval setImmediate I/O callbacks How it works: Executes after the call stack is empty Runs only when no microtasks are pending Lower priority ⬇️ 2️⃣ Microtask Queue Handles: Promise.then / catch / finally async / await MutationObserver queueMicrotask() How it works: Executes immediately after synchronous code Fully drained before moving to the callback queue Higher priority ⬆️ 💻 Example Code console.log('1. Sync'); setTimeout(() => { console.log('2. Callback Queue'); }, 0); Promise.resolve().then(() => { console.log('3. Microtask Queue'); }); console.log('4. Sync'); 📤 Output 1. Sync 4. Sync 3. Microtask Queue 2. Callback Queue ⚙️ Execution Flow Run all synchronous code Execute all microtasks Execute one macrotask Repeat the cycle 🎯 Why This Matters Explains why Promise callbacks run before setTimeout(0) Helps debug race conditions and timing issues Critical for performance-sensitive UI logic Commonly asked in JavaScript & Frontend interviews Once this clicks, async JavaScript stops feeling “magical” and becomes predictable. #JavaScript #EventLoop #AsyncJavaScript #FrontendDevelopment #WebDevelopment #Promises #Microtasks #JavaScriptTips #InterviewPreparation #CodingConcepts #FrontendEngineer
To view or add a comment, sign in
-
-
Day 15/365 – Advanced JavaScript Interview Questions 🔥 Part4 Q1. Explain the JavaScript event loop in detail. How do microtasks and macrotasks work? Q2. What are memory leaks in JavaScript? How do you detect and prevent them? Q3. How does garbage collection work in JavaScript? Q4. What is execution context? Explain call stack, heap, and scope chain. Q5. How does this behave in different scenarios (strict mode, arrow functions, callbacks, event handlers)? Q6. What are weak collections (WeakMap, WeakSet)? When would you use them? Q7. Explain immutability. Why is it important in large-scale applications? Q8. What are design patterns you’ve used in JavaScript? (Module, Singleton, Observer, Factory) Q9. How does prototype chaining work internally? Q10. What is the difference between Object.create() and constructor functions? Q11. How do you handle race conditions in async JavaScript? Q12. What are web workers? When should you use them? Q13. How does JavaScript handle concurrency despite being single-threaded? Q14. What are pure functions? Why are they important for scalability and testing? Q15. How does debouncing/throttling differ from requestAnimationFrame-based optimizations? Q16. Explain deep cloning strategies and their performance trade-offs. Q17. How does tree shaking work in JavaScript bundlers? Q18. What is code splitting and how does it improve performance? Q19. How do you design a reusable and scalable JavaScript utility library? Q20. What JavaScript performance issues have you faced in production and how did you fix them? #javascript #interview #jsinterview #interiewprepration #webdevelopment #js #performace #optimization #365daysofjs
To view or add a comment, sign in
-
🤔 Ever confused by the three dots (...) in JavaScript? They look the same, but default parameters, rest, and spread solve very different problems. 🧠 JavaScript interview question What’s the difference between default parameters, rest parameters, and the spread operator? ✅ Short answer • Default parameters give fallback values • Rest collects multiple values into one • Spread expands one value into many Same syntax, different intent. 🔍 Default parameters — “Give me a fallback” Used when a function argument is missing or undefined. Instead of manual checks, JavaScript handles it for you. function greet(name = "there") { return "Hi " + name; } greet(); // "Hi there" greet("Sam"); // "Hi Sam" 🔍 Rest parameters — “Collect the leftovers” Used in function definitions to gather extra arguments into a real array. function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3, 4); // 10 🔍 Spread operator — “Unpack things” Used in function calls, arrays, and objects to expand values. const a = [1, 2]; const b = [3, 4]; const combined = [...a, ...b]; // [1,2,3,4] With objects (shallow copy): const user = { name: "A", meta: { v: 1 } }; const copy = { ...user, role: "admin" }; ⚠️ Common misconceptions • Rest ≠ arguments (rest is a real array) • Spread does not deep clone objects • Default params apply only when value is undefined 🧩 Easy way to remember Rest gathers. Spread scatters. #javascript #frontend #webdevelopment #interviewprep #react #codingtips
To view or add a comment, sign in
-
Type Conversion in JavaScript ---------------------------------------- JavaScript supports three main types of type conversion: > String Conversion > Number Conversion > Boolean Conversion > String Conversion Use the String(value) method to convert a value into a string. Examples: String(10) // "10" String(true) // "true" String(false) // "false" String(null) // "null" > Number Conversion Use the Number(value) method to convert a value into a number. If conversion fails, it returns NaN. Examples: Number("10") // 10 Number("sdfsd") // NaN Number(false) // 0 Number(true) // 1 Number("") // 0 > Boolean Conversion Use the Boolean(value) method to convert a value into a boolean. Examples: Boolean(1) // true Boolean(0) // false Boolean("true") // true Boolean("") // false Boolean(null) // false Boolean(undefined) // false #JavaScript #JavaScriptBasics #TypeConversion #WebDevelopment #FrontendDevelopment #Programming #Coding #SoftwareDevelopment #WebDevelopers #LearnJavaScript #DeveloperCommunity #TechLearning #CodingTips #ITCareers
To view or add a comment, sign in
-
Controlling `this` in JavaScript: Call vs. Apply vs. Bind. 🎮 One of the most common interview questions for mid-level developers is: "𝑊ℎ𝑎𝑡 𝑖𝑠 𝑡ℎ𝑒 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑐𝑒 𝑏𝑒𝑡𝑤𝑒𝑒𝑛 𝐶𝑎𝑙𝑙, 𝐵𝑖𝑛𝑑, 𝑎𝑛𝑑 𝐴𝑝𝑝𝑙𝑦?" They all do the same core job: They allow you to manually set what `this` refers to inside a function. But they do it in slightly different ways. 𝐇𝐞𝐫𝐞 𝐢𝐬 𝐭𝐡𝐞 𝟏𝟎-𝐬𝐞𝐜𝐨𝐧𝐝 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧: 1️⃣ 𝐂𝐚𝐥𝐥 & 𝐀𝐩𝐩𝐥𝐲 (𝐓𝐡𝐞 𝐈𝐦𝐦𝐞𝐝𝐢𝐚𝐭𝐞 𝐈𝐧𝐯𝐨𝐤𝐞𝐫𝐬) Both of these execute the function 𝑖𝑚𝑚𝑒𝑑𝑖𝑎𝑡𝑒𝑙𝑦. The only difference is how they handle arguments. • 𝐂𝐚𝐥𝐥: Passes arguments individually (comma-separated). • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐂all = 𝐂ommas. • 𝐀𝐩𝐩𝐥𝐲: Passes arguments as a single Array. • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐀pply = 𝐀rray. 2️⃣ 𝐁𝐢𝐧𝐝 (𝐓𝐡𝐞 𝐏𝐥𝐚𝐧𝐧𝐞𝐫) • 𝐁𝐢𝐧𝐝: Does NOT execute the function immediately. • Instead, it returns a 𝐧𝐞𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐜𝐨𝐩𝐲 with the `this` context permanently locked (bound) to the object you specified. You can then call this new function whenever you want later. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? It allows "Method Borrowing." You can use a method from one object (like a helper function) and use it on a completely different object, just by changing the `this` context! Check out the syntax comparison below! 👇 Which one do you use most often? I find `bind` essential for passing methods into React components or event listeners! #JavaScript #WebDevelopment #CodingInterviews #SoftwareEngineering #Frontend #JSConcepts
To view or add a comment, sign in
-
-
🤔JavaScript behaves differently with values depending on what you’re working with and this trips up a lot of interview answers. 🧠 JavaScript interview question What is the difference between primitive and reference types? ✅ Short answer • Primitives are copied by value • Objects are copied by reference • Equality checks references, not structure 🔍 A bit more detail • Primitive types number, string, boolean, null, undefined, symbol, bigint Stored as values Assigning or passing them creates a copy • Reference types objects, arrays, functions Variables store a reference to the same object Mutating through one reference affects all others • Equality {} === {} is false Same shape does not mean same reference 💻 Example // primitive copy let a = 5 let b = a b = 7 console.log(a) // 5 // reference copy const p = { n: 1 } const q = p q.n = 2 console.log(p.n) // 2 ⚠️ Small but important detail JavaScript always passes arguments by value. For objects, that value is the reference. Reassigning a parameter does nothing. Mutating the object does. I’m sharing one JavaScript interview-style question per day to build calm, solid fundamentals step by step. #javascript #frontend #interviewprep #webdevelopment
To view or add a comment, sign in
-
Day 13/50 – JavaScript Interview Question? Question: What is hoisting in JavaScript? Simple Answer: Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase. Function declarations are fully hoisted, var declarations are hoisted but initialized as undefined, and let/const are hoisted but remain in the Temporal Dead Zone. 🧠 Why it matters in real projects: Understanding hoisting helps you avoid confusing bugs and write more predictable code. It explains why you can call functions before they're declared and why accessing var variables before declaration returns undefined instead of an error. 💡 One common mistake: Thinking hoisting physically moves code. It doesn't—it's about when variables and functions are registered in memory during the creation phase. 📌 Bonus: // Function hoisting - works! greet(); // "Hello" function greet() { console.log("Hello"); } // var hoisting - returns undefined console.log(name); // undefined (not ReferenceError) var name = "Alice"; // let/const - Temporal Dead Zone console.log(age); // ReferenceError let age = 25; // Function expressions are NOT fully hoisted sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log("Hi"); }; #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🤔 JavaScript behaves the way it does for a reason. Type coercion exists so different values can interact without throwing errors all the time. But if you don’t know the rules, it can feel unpredictable. 🧠 JavaScript interview question What is type coercion in JavaScript? ✅ Short answer • JavaScript automatically converts values between types when needed • This can happen implicitly or explicitly • Operators decide how and when conversion happens 🔍 A bit more detail • Implicit coercion Happens during operations like +, -, ==, or Boolean checks • Explicit coercion You force conversion using Number(), String(), Boolean() • The + operator If one side is a string, it concatenates Otherwise, it tries numeric addition • Equality == Tries to convert both sides to a common type before comparing "10" + 5 // "105" "10" - 5 // 5 0 == false // true "" == 0 // true null == undefined // true ⚠️ Small but important detail Only the empty string is false when converted to Boolean. "0" is a non empty string, so it is true. Boolean("") // false Boolean("0") // true I’m sharing one JavaScript interview style question every day so we can all build stronger fundamentals together. #javascript #frontend #webdevelopment #interviewprep
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